-1
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?

Scrapper142
  • 566
  • 1
  • 3
  • 12

1 Answers1

3
  1. str will not be resized. It just occupys the memory after str beyond compiler's comprehension. It may cause unexpected consequences.

  2. 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
  1. Or another possibility, your compiler allocate a after str. Therefore, a can't be affected by str. 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
  • Another possibility is the compiler does not even allocate any space for `a` as it can replace it by its value `20` is the `printf` statement. Also insist on undefined behavior being **undefined** so nothing can be expected. – chqrlie Jun 14 '22 at 07:28
  • Yes, this is closely related to compiler optimizations. The right way is not to depend on undefined behavior. – Autumnal_Joy Jun 14 '22 at 07:56