Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable declaration and their memory addresses in C

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:

enter image description here


I tested the same program in many type of variables , the results i gets are ..

When variables are char type. enter image description here


When variables are long type enter image description here


When i declare int array , size each array is 1. enter image description here


When size of second declared array is 2 , it gets extra 4 byte offset. enter image description here

like image 374
siddstuff Avatar asked May 15 '13 21:05

siddstuff


2 Answers

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?

like image 110
Steve Avatar answered Dec 16 '22 21:12

Steve


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.

like image 40
Mats Petersson Avatar answered Dec 16 '22 21:12

Mats Petersson