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.
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:
The difference between two pointers is defined only for pointers into or just past the end of the same array (C23 6.5.7/10). Your program attempts to compute the difference between pointers that do not have such a relationship, so anything could happen.
Even if we assumed, with no basis in the language spec, that pointer differences were computed in a flat global address space, C says nothing about where automatic variables are allocated, neither in absolute terms nor in relative ones, so you would still have no basis for any expectation about the result of the pointer difference. In particular, C does not assume the use of a stack, and it certainly says nothing about the direction in which such a stack might grow.
Even if we additionally assumed, with no basis in the language spec, that the machine uses a call stack to manage storage for automatic objects, AND that that stack grows downward, C still does not guarantee that automatic objects are allocated so that the addresses of consecutively declared objects track the direction of stack growth. That might be a more reasonable assumption in an interpreted language, where we might suppose that space is allocated in the order that control reaches variable declarations, but C is not (generally) such a language.
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.