char str[] = "some short string";
int a = 20;
strcat(str, "a very very long string");
printf("%d\n", a); // prints 20
If I understand correctly, a
is added to the stack directly above str
. But this should mean that when str
is resized to take up more space, it should overwrite the memory space a
is using. How does this still print 20?
CodePudding user response:
str
will not be resized. It just occupys the memory afterstr
beyond compiler's comprehension. It may cause unexpected consequences.Understanding stack allocation and alignment There is some space after
str
. The size of space depends on various compilers. In my PC, the program does not print 20, but a meaningless number.
----------------- high address
| <function info> |
-----------------
| <a> |
-----------------
| <empty space> |
-----------------
|gnirts trohs emos| "some short string"
-----------------
| | <- stack pointer
| | low address
- Or another possibility, your compiler allocate
a
afterstr
. Therefore,a
can't be affected bystr
. The compiler decides the order of memory allocation.
----------------- high address
| <function info> |
-----------------
| <empty space> |
-----------------
|gnirts trohs emos| "some short string"
-----------------
| <a> |
-----------------
| | <- stack pointer
| | low address