0

For this code

#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j, k, l;
int *ii = (int *)malloc(sizeof(int));
int *jj = (int *)malloc(sizeof(int));
int *kk = (int *)malloc(sizeof(int));
int m, n, o, p;
// Call below line as star line
printf("%u %u %u %u %u %u %u %u %u %u %u\n",&i,&j,&k,&l,&ii,&jj,&kk,&m,&n,&o,&p);
// Call below line as delta line
printf("%u %u %u %u %u %u %u %u %u %u %u\n",&i,&j,&k,&l,ii,jj,kk,&m,&n,&o,&p);
 return 0;
}

I'm getting this output

2293516 2293512 2293508 2293504 2293500 2293496 2293492 2293488 2293484 2293480 2293476
2293516 2293512 2293508 2293504 3739288 3739320 3739336 2293488 2293484 2293480 2293476

Everything is clear till now but when I commented the star line output becomes

2293520 2293516 2293512 2293508 4525720 4525752 4525768 2293504 2293500 2293496 2293492

My question is why in this case memory locations are not contiguous. In second line of first case values were at regular difference of 4 bytes i.e. 516, 512, 508, 504, and then three locations and then 488, 484, 480... but in second case values are 520, 516, 512, 508, and then three locations and then 504, 500, 496. Why here next value after 508 is 504 while it should be 492? Is there any role of printf here?

Bharat Kul Ratan
  • 985
  • 2
  • 12
  • 24

1 Answers1

2

The compiler is free to arrange local variables in memory however it sees fit.

There is no guarantee that local variables are stored contiguously, or that there is not unnamed padding between them, or that they are stored in a particular order in memory.

There is also no guarantee that a local variable actually exists at runtime at all. For example, when you comment out the first printf, the local variables ii, jj, and kk are never used as lvalues (basically, you never do anything that requires the address of the objects), so the compiler may choose to eliminate those variables entirely.

In your specific example, a compiler might decide to store all three variables at the same location in memory, or--since you never initialize the variables--it may just use the random contents of some other location in memory, which would be equally "valid" behavior.

James McNellis
  • 348,265
  • 75
  • 913
  • 977