#include<stdio.h>
#include<string.h>
int main()
{
char a[]="aaa";
char *b="bbb";
strcpy(a,"cc");
printf("%s",a);
strcpy(b,"dd");
printf("%s",b);
return 0;
}
We could not modify the contents of the array but the above program does not show any compile time error.When run it printed cc and terminated. The contents of the array i think will get stored in the read only section of the data segment and so its not possible to change the value of array as its a const.But here in the above program the value got changed to cc and the program terminated.The value got changed here why is it so.Please help me understand.
Here’s a hypothetical memory map showing how the string literals, array, and pointer all relate to each other:
This is the situation at line 6 in your code, after
aandbhave been declared and initialized. The string literals"aaa","bbb","cc", and"dd"all reside somewhere in memory such that they exist over the lifetime of the program. They are stored as arrays ofchar(const charin C++). Attempting to modify the contents of a string literal (in the case of this hypothetical, attempting to write to any memory location starting with 0x0004) invokes undefined behavior. Some platforms store string literals in read-only memory, some store them in writable memory, but in all cases, they should be treated as though they are unwritable.The object
ais an array ofchar, and it has been initialized with the contents of the string literal"aaa". The objectbis a pointer tochar, and it has been initialized with the address of the string literal"bbb". In the lineyou’re copying the contents of the string literal
"cc"toa; after the line is executed, your memory map looks like this:So when you print
ato standard output, you should see the stringcc. Note:printfis buffered, so it’s possible that output may not be written to the terminal immediately – either add a newline character to the format string (printf("%s\n", a);) or callfflush(stdout);after theprintfto make sure all your output shows up.In line 9, you attempt to copy the contents of the string literal
"dd"to the location pointed to byb; unfortunately,bpoints to another string literal, which as mentioned above invokes undefined behavior. At this point, your program could literally do anything from run as expected to crash outright to anything in between. This could be part of the reason you only see the output forcc.