int main(void)
{
char *ptr;
ptr = malloc(sizeof(char)*20);
printf(“%p\n”, ptr);
ptr = “hello”;
printf(“%p\n”, ptr);
printf(“The sting is %s\n”, ptr);
free(ptr);
return 0;
}
Check the above program. Ptr address is different in first and second case. Also free will give segmentation error. Because allocated mem and where hello string is there are different. So the correct way of copying string is strcpy(ptr, “hello”) and not by ptr = “hello”;
yes you are right,
this is because when you use malloc function it holds the space in heap but in case of assigning “Hello” string to a pointer, first the string is stored in Read only section of stack and then the address of this stack location is assigned to ptr.
thats why you’ll get segmentation fault in free(ptr) statement.
Also by doing this u’ll not able to free that memory ever in you program.