I created a simple program:
#include <stdio.h>
int main()
{
int s1;
int s2;
int s3;
int *p1, *p2, *p3;
p1 = &s1;
p2 = &s2;
p3 = &s3;
printf("%d\n%d\n%d", p1, p2, p3);
}
Whenever I run this program, it prints the memory addresses of pointers p1
, p2
and p3
and the interesting thing is that these values have differences of 12
. I want to know the reason behind this. Why do the addresses differ by 12
?
Note: This happens each time I execute the program.
Output:
I tested the same program in many type of variables , the results i gets are ..
When variables are char type.
When variables are long type
When i declare int array , size each array is 1.
When size of second declared array is 2 , it gets extra 4 byte offset.
I'm guessing this is a debug build. I've tried this program built with Visual Studio 2010. On debug there is a 12 byte difference between addresses. In release mode there is a 4 byte (sizeof(int)
) difference.
In debug builds the MSVC compiler adds in extra data to help detect buffer overflows and use of uninitialized memory. If you put a break point on your printf
statement and view the memory pointed to by p1
you should see cc
in the memory.
There are a number of different magic values that memory is initialized to. cccccccc
indicates uninitialzed stack space. For a more detailed list, see the answer to this question: In Visual Studio C++, what are the memory allocation representations?
I'm fairly sure that this is a case of "compiler puts extra stuff in to detect when you write to places you shouldn't". Micrsoft does like to do this, so that it can detect when your code is doing bad stuff. Try something like:
void func()
{
int x = 18;
int *px = &x;
px[1] = 4711;
cout << "px = " << px << " x = " << x << " px[1] = " << px[1] << endl;
}
and see if the compiler doesn't "detect" that this code is doing bad stuff... If it does, it's because it's put "padding" between x and and p, and checks when the function returns that those "padding" areas haven't been touched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With