// file1.c
char str[] = "abcd";
// file2.c
#include <stdio.h>
extern char *str;
int main()
{
str[0] = 'A';
printf("%s", str);
}
编译正常,运行崩溃,为什么?
PHPz2017-04-17 14:39:30
There is a difference between
char str[]
and char *str
. str[] is the name of the array and is a label. Although str is the first address of the array, str[] itself does not occupy space and is just a symbol. And char *str
takes up 4 bytes (8 bytes for 64 bits).
Assuming that on a 32-bit machine, the linker will change the 4 bytes starting from str[] (i.e. str[0], str[1], str[2], str[3]) when linking. The value stored inside is copied to the 4-byte memory space where *str
is located. This means that the value of the 4-byte memory space occupied by *str
becomes a concatenated ascii value of "abcd". value. Therefore, *str
points to an unknown area, and reading and writing to this unknown area may trigger segmentation fault
.
If you execute printf("%d",str); on *str
, the value should be (little endian)
97 + 98*256 + 99*256*256 + 100*256*256*256
Addition: There is an error in the above explanation. *str
In fact, 4 bytes of storage space is not allocated because it is extern. To put it figuratively, *str is "a hot face but a cold butt" 贴
to str[]. The error mechanism is the same.