I have two files:
extern char *s;
int main()
{
puts(s);
}
char s[] = "hello";
I compile both of them at same time, there's no error. But program crashes when run. Why? What part of the C language specification says that this is illegal?
You invoked undefined behavior and the program happened to crash.
Quote from N1256 6.2.7 Compatible type and composite type
1 Two types have compatible type if their types are the same. Additional rules for determining whether two types are compatible are described in 6.7.2 for type specifiers, in 6.7.3 for type qualifiers, and in 6.7.5 for declarators. [...]
2 All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined.
In typical environment, when the program is run, what is stored will be read as pointer because the declaration says that a pointer is there in a.c
, but what actually is a part of string (if size of pointers is 4 bytes) and it has little chance of being valid pointer. Therefore, reading from that address has a big chance of causing a Segmentation Fault.