Char * str = "resource ";
Str [6] = k; // memory write error reported
* (Str + 6) = k; // the same error is reported when writing this code.
But there is no problem:
Char * str = new char [12];
Strcpy (str, "resource ");
Str [6] = k; // No problem
* (Str + 6) = k; // No problem
This is OK:
Char str [] = "resource ";
Str [6] = k;
* (Str + 6) = k;
After searching for information on the Internet, I found a more accurate answer:
"Resource" is a String constant.
For char * str = "resource ";
The starting address is the value of "resource", that is, the literal value of the String constant, that is, the address of "resource". Specifically, it is the starting address ---- assigned to the character pointer str. in Linux, the "resource" String constant is stored in the read-only data zone. Generally, on 32-bit machines, in Linux, heap, global data, constants and so on are stored in the memory address starting from 0x8048000, increasing upwards. You can print the "resource" address for verification. Char * str = "resource" is to assign the first address of "resource" to str, so str stores the address of a read-only data zone, writing data in the read-only zone is forbidden. The specific operating system determines and processes the data.
For char str [] = "resource ";
Str [] is a character array. The Compiler first allocates a certain amount of continuous space in the stack to store the characters and terminologies in the "resource", and then stores the content of the String constant, that is
The characters and terminologies in "resource" are copied to the continuous space in this stack. Str is the array name used to indicate the starting address of the continuous stack space. Therefore, str stores the stack address, and the data of this address is writable. Generally, on 32-bit machines, in Linux, the stack address space increases from 3 GB (0 xbfffffff) down.
You can use the printf ("% x", str) statement to print the address stored in str to verify whether the address belongs to the stack or the read-only data zone.