In the first case, I am clear that memory will be allocated on stack.
not necessarily. it depends on where the variable is defined. if it's a global variable for example, the memory will be allocated on a read/write data segment. but yes, in case it's local, the memory will be allocated on the stack.
In the second case, I think there will be problem because x is having some random memory location and when it is tried to de-reference then there will be issue. But still, will be on stack or heap?
well, clearly x
doesn't point to anything at the moment you're are to assign it. such operation has an undefined behavior (very bad) and may certainly cause problems.
however, in case you're dealing with pointer, you need to differentiate between two memory locations:
- the location where the pointer stores the address.
- the location that the pointer points to (begins at the stored address).
in case of
int *p;
there is memory allocated for p
to store an address and where this location is totally depends on where p
is defined just like the case above.
when you do
p = malloc(sizeof(int));
and assuming everything goes well, this allocates memory for p
to point to (specifically of size sizeof(int)
). this memory is gonna be on the heap.
how the things would be different in below 2 cases
see How can char* contain a collection of characters instead of a memory address?How can char* contain a collection of characters instead of a memory address?