1

I'm writing a simple code for removing spaces from a string in C however I get the following message after compiling: EXC_BAD_ACCESS (code=2, adresss=....). It's coming from the line '*temp = *str' however I don't understand why? How can I fix it?

void removeSpaces(char * str)
{
  char * temp = str;

  while (*str != '\0') {
    if (*str != ' ') {
      *temp = *str;
      temp++;
     }
    str++;
  }
  *temp = '\0';
}
2
  • Hint: compare char * temp = str and *temp = *str. Commented May 7, 2015 at 8:11
  • 7
    How did you call removeSpaces()? Did you pass it a string literal? Commented May 7, 2015 at 8:17

2 Answers 2

8

The function works fine when passed a string declared like this

char s[] = "Hallo  World!";

but if you declared the string like this, as a pointer to string literal

char *s = "Hallo  World!";

you are not supposed to modify the string.

Sign up to request clarification or add additional context in comments.

1 Comment

@WeatherVane impressive answer. Actually I am contempleting your answers and it seems there is so much I can learn. Thanks for being here. Will check out your answers time and again to learn more.
2

It seems that you are passing an string literal. temp and str pointing to same string literal. With statement *temp = *str; you are modifying the that literal which should not be modified.

To fix the problem allocate memory for temp

char *temp = malloc(strlen(str) + 1);   

3 Comments

He can modify directly the same string
I suggest mentioning about strdup here. Also, about freeing the allocated memory.
It's not a problem to modify the same string, in fact, it's better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.