Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An observation about variable memory addresses in C

I have a question rather than a problem (witch maybe arises a memory question).. I've written this simple program:

#include <stdio.h>
#include <stdlib.h>

int multi(int x, int y);


int main(){
    int x;
    int y;
    printf("Enter the first number x: \n");
    scanf("%d",&x);
    printf("Enter the second number y: \n");
    scanf("%d",&y);
    int z=multi(x,y);
    printf("The Result of the multiplication is : %d\n",z,"\n");
    printf("The Memory adresse of x is : %d\n",&x);
    printf("The Memory adresse of y is : %d\n",&y);
    printf("The Memory adresse of z is : %d\n",&z);
    getchar();
    return 0;
}

int multi(int x,int y){
    int c=x*y;
    printf("The Memory adresse of c is : %d\n",&c);
    return c;  
}

As you can see (if you develop in C), this program inputs 2 int variables, then multiplies them with the multi function:

after getting the result , it displays the location of each variable in the memory (c,x,y and z).

I've tested this simple example those are the results (in my case):

The Memory adresse of c is : 2293556  
The Result of the multiplication is : 12  
The Memory adresse of x is : 2293620  
The Memory adresse of y is : 2293616  
The Memory adresse of z is : 2293612  

as you can see , the three variables x,y,z that are declared in the main function have closed memory adresses (22936xx) , the variable c that's declared in the multi function has a different adress (22935xx).

looking at the x,y and z variables, we can see that there's a difference of 4 bytes between each two variables (i.e : &x-&y=4, &y-&z=4).

my question is , why does the difference between every two variable equals 4?

like image 652
SmootQ Avatar asked Nov 23 '25 09:11

SmootQ


2 Answers

x, y, and z, are integer variables that will be created on the call stack (but see below). The sizeof int is 4 bytes, so that is how much space a compiler will allocate on the stack for those variables. These variables are adjacent to one another, so they are 4 bytes apart.

You can read about how memory is allocated for local variables by looking for information on calling conventions.

In some cases (where you do not use the address-of operator), the compiler may optimize local variables into registers.

like image 198
Emil Sit Avatar answered Nov 24 '25 21:11

Emil Sit


In your situation the three variables were allocated in contiguous memory blocks. On x86 systems, int types are 32-bits wide, i.e. sizeof(int) == 4. So each variable is placed 4 bytes apart from the last.

like image 29
逆さま Avatar answered Nov 24 '25 21:11

逆さま



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!