Search code examples
cstringpointersstring-literals

Why C program crashes?


Please, someone explain why the following C program crashes:

void changeChar(char *string);

int main(int argc, char *argv[])
{
  char *test = "word";
  changeChar(test);
  return 0;
}

void changeChar(char *string) {
  *string = 'A';
}

while the following code works perfectly:

void changeChar(char *string);

int main(int argc, char *argv[])
{
  char test[] = "word";
  changeChar(test);
  return 0;
}

void changeChar(char *string) {
  *string = 'A';
}

Solution

  • Because

    char *test = "word";
    

    is not the same as

    char test[] = "word";
    

    The first one is string literal it MUST not be changed - changing it causes undefined behavior (as they are immutable).

    The second one is a standard (mutable) array of chars.

    By the way, the first one must be const char*, not char* (and this will even solve the issue - you'll get compile time error) (thanks to @ouah and @dasblinkenlight - didn't know, that there's a difference in this case)