EmbLogic's Blog

Something important abt pointer

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”;

One Response to Something important abt pointer

  1. nitin sharma says:

    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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>