Will a pointer declaration to a structure allocate memory for its members?

  • A+

check the image of program on turbo c++

output of program

#include< stdio.h>  struct node  {     int data; };  int main() {      struct node *ptr;      ptr->data=3;     printf("%d",ptr->data);      return 0; } 

Output: 3

My question is that even though I have not declared an instance of structure node.

e.g struct node n;

Also I have not assigned memory for ptr using malloc, it still allocates space for ptr->data. Why? Shouldn't it just assign memory for address ptr on stack.

And where this memory for data field is allocated, on stack or heap.---------


In your code, ptr->data=3; invokes undefined behavior, as ptr does not point to any valid memory location.

You need to make sure that ptr points to a valid memory location before making any attempt to de-reference it.

It appears to work properly in your case, that is also one of the most dangerous side effects of undefined behavior.

That said, ptr is having automatic storage. The memory it would point to, will depend on the allocation used. C standard does not have a notion of stack or heap - that is dependent on the implementation.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: