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.
Also I have not assigned memory for ptr using malloc, it still allocates space for ptr->data.
Nothing's been allocated. Without an initializer, the value of ptr is indeterminate, and in this case just happens to point to memory that you can write to without immediately crashing your program. You managed to not overwrite anything "important", but that's a matter of luck more than anything else.
You should get in the habit of initializing pointers as you declare them, either as NULL or as the result of the & operator or as the result of a malloc/calloc/realloc call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With