clinuxstructstackmemory-layout

Stack Memory Layout


I understand stack moves from Higher memory address to Lower memory address,To find the size of the structure without using any library calls i used below logic,

#include <stdio.h>

typedef struct node{
    int a;
    char b;
    int c;
} Node;

int main(){
    Node obj1;
    Node obj2;
    printf("Size of struct is %ld\n",(char*)&obj1 - (char*)&obj2);
    return 0;
}

The result is -12, what makes the result -ve. I tried disabling the compiler optimizations as well.

The expectation is the difference between the obj1 and obj will be +ve since obj1 will be first allocated in stack with a higher address and then followed by obj2.


Solution

  • The expectation is the difference between the obj1 and obj will be +ve since obj1 will be first allocated in stack with a higher address and then followed by obj2.

    The C language provides no basis whatsoever for such an expectation:

    So, why do you get a result of the form you do? Details of your C implementation, and possibly circumstances of your particular run of the program. It is rarely useful to analyze undefined behavior.