Home > OS >  How does strcat not overwrite the next variable?
How does strcat not overwrite the next variable?

Time:06-14

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:

  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
  • Related