Modifying C string constants? [duplicate]

Since you’re studying for an exam, I’ll flesh out my comments a bit to explain what’s actually happening:

char *str = "abc";

str is a pointer stored on the stack. It gets initialized to point to the literal string "abc". That literal string is going to be stored in the data section of your compiled executable and gets loaded into memory when your program is loaded. That section of memory is read-only, so when you try and modify the data pointed to by str, you get an access violation.

char* str = malloc(sizeof(char) * 4);
strcpy(str, "abc");

Here, str is the same stack pointer as the first example. This time, it is initialized to point to a 4-character block of memory on the heap that you can both read and write. At first that block of memory is uninitialized and can contain anything. strcpy reads the block of read-only memory where “abc” is stored, and copies it into the block of read-write memory that str points to. Note that setting str[3] = '\0' is redundant, since strcpy does that already.

As an aside, if you are working in visual studio, use strcpy_s instead to make sure you don’t overwrite your buffer if the string being copied is longer than you expected.

char str[] = "abc"; 

Here str is now an array allocated on the stack. The compiler will sized it exactly fit the string literal used to initialize it (including the NULL terminator). The stack memory is read-write so you can modify the values in the array however you want.

char str[4] = "abc";

This is effectively the same as the previous version, only you are telling the compiler that you know better than it does how long the array should be. You may get into trouble if you change the string and not the array size.

Leave a Comment