Domanda

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';
}
È stato utile?

Soluzione

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)

Altri suggerimenti

The first program crashes because it tries to write the memory allocated to a string literal, which is an undefined behavior. The second program copies the string literal into writable memory, fixing the problem.

Because char *test = "word"; defines a pointer to constant string literal that resides within the read-only memory. Trying to modify it results in undefined behavior.

Also have a look at:
What is the difference between char s[] and char *s?

And since this is quite common mistake, you'll find many duplicates:
Why do I get a segmentation fault when writing to a string initialized with "char *s" but not "char s[]"?
C: differences between char pointer and array
Is it possible to modify a string of char in C?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top