Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When defining a variable in C for example, where is the memory address for that variable stored?

If I define a variable in C (i.e. unsigned short int n = 5), that value is stored somewhere in the user's RAM in binary (in this case it would look something like 0000 0000 0000 0101). The place in which that value is stored has an address that is also in binary. (i.e. the value 5 could be stored at say 0010 which would mean it uses both 0010 and 0011 in ram since it uses 2 bytes). The name of the variable n represents the memory address where that value is stored. Where is that memory address stored? Wouldn't that take up even more ram? If it did then wouldn't that address have to have an address as well?

like image 576
William Oliver Avatar asked Dec 23 '12 21:12

William Oliver


2 Answers

The memory address of a variable is not stored directly in memory. It is part of the code that accesses the variable. Depending on the exact circumstances, it's either an offset (distance from a known place - for example the stack pointer for a local variable, and for a global variable it may be the program counter) or an absolute address (only for global variables).

If you want a variable to store the address of a variable, then yes, you need memory for that variable too. This type of variable is called a pointer.

like image 158
Mats Petersson Avatar answered Sep 28 '22 07:09

Mats Petersson


It depends on several factors, such as the allocation method (stack or static), how the variable is accessed, but let's assume this piece of code:

static int n = 5;
printf("%p\n", &n);

In this case, the address of n is stored in the code segment, where printf is called. If you disassemble the code, you'll find a push instruction, pushing an address to the stack, right before calling printf. The address being pushed is the address of n (it's one of two addresses being pushed, there's also the format string).

As I said above, it isn't always the same way. Different architectures and compilation flags (e.g. -fpic) can change it.
Also, if the variable is on the stack, or if the reference to it is not from code, but from data (e.g. int n=5; int *p = &n;), things change.

like image 44
ugoren Avatar answered Sep 28 '22 09:09

ugoren