简体   繁体   中英

Removing spaces from a string in C Memory fault

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';
}

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.

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);   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM