We have a code as below:
#include<stdio.h>
#include<unistd.h>
#include<string.h>
main()
{
char *i;
const char ch = 'a';
strcpy(i,&ch);
printf("%lx %lx %c",sbrk(0),i , *i);
}
This program throws segemtation fault. But when strcpy is replaced by " *i = ch; " , this one works.
As we understand, for local variables we get a memory in stack as long as we dont do
malloc . But then simple assignment should also fail because "i" hasnt been allocated any memory before assignment.
How exactly a memory is allocated in this case.
As we see in printf , sbrk gives us the end of heap address. This value turns out to be more than i's value. If stack is allocated in higher memory address than heap , then this shows that i refers to a memory in heap and not in stack.
Please throw some light on this.
Start Free Trial