Does only malloc()
allocate memory on the heap or when we use pointer and normal variables put some value then it will be stored in some memory location on heap.
To be clear, below are cases:
//First case:
int x = 10;
//Second case:
int* x;
*x = 10;
//Third case:
int* x = malloc(sizeof(int));
*x = 10;
Could you please confirm my below understanding:
- In the first case, I am clear that memory will be allocated on 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? - In the third case, memory will be on heap.
Now, in the second case we have seen that there will be an issue because of random access of memory, but how the things would be different in below 2 cases:
//4th case
char* str1;
str1 = "asdasd";
//5th case
char* str2 = "asdasd";
Could you please answer:
- In above 2 cases, where the memory will be allocated?
- If we had done, 5th case using
int*
asint* x = 10;
thenx
would have ended up as holding memory location10
but when we do same thing usingchar*
then string is successfully stored. Why?
Could you please provide all above answers.
I am really confused with in C, in what all scenarios (like using malloc
or just by using pointer) memory will be allocated in heap and stack. And more confusion comes when things work differently with char*
and int*