简体   繁体   中英

c variables allocation on memory, pointers

How are variables are located in memory? I have this code

int w=1;
int x=1;
int y=1;
int z=1;

int main(int argc, char** argv) {
    printf("\n  w %d",&w);
    printf("\n  x %d",&x);
    printf("\n  y %d",&y);
    printf("\n  z %d",&z);
    return (EXIT_SUCCESS);
}

and it prints this

w 134520852
x 134520856
y 134520860
z 134520864

We can see that when other integer is declare and assigned, the address is moved four positions (bytes I suppose, it seems very logic). But if we don't assign the variables, like in the next code:

int w;
int x;
int y;
int z;

int main(int argc, char** argv) {
    printf("\n  w %d",&w);
    printf("\n  x %d",&x);
    printf("\n  y %d",&y);
    printf("\n  z %d",&z);
    return (EXIT_SUCCESS);
}

it prints this

w 134520868
x 134520864
y 134520872
z 134520860

We can see there are four positions between addresses, but they are not in order. Why is this? How works the compiler in that case?

In case you want to know why I'm asking this, it is because I'm starting to study some security and I'm trying to understand some attacks, for instance, how integer overflow attacks work, and I've been playing with pointers in C to modify other variables by adding more positions than the size of the variable and things like that.

Your first example initialises variables, which generates different allocation code. By looking into the assembly file generated by gcc (gas) I get:

    .globl  _w
    .data
    .align 4
_w:
    .long   1
    .globl  _x
    .align 4
_x:
    .long   1
    .globl  _y
    .align 4
 _y:
    .long   1
    .globl  _z
    .align 4
 _z:
    .long   1

And this basically dictates the memory addresses.

Your second example creates uninitialised variables, and as Jonathan said, those go into BSS . The assembler code is:

.comm  _w, 4, 2
.comm  _x, 4, 2
.comm  _y, 4, 2
.comm  _z, 4, 2

And that means you can't guarantee the sequence in which those variables will be located in memory.

The second set of numbers is also consecutive, just not ordered the same as in the source. I think the reason for this is simply that when you initialize the variables the compiler puts them in order because it maintains the order of initializations, in the second case you just get a random order.

In any case this depends on the compiler; I get the same pattern (ordered, 4 bytes apart) in both cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM