-1

We are using : Turbo C3 Compiler on Windows XP.

We have a question for following code snippet:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
  void main()
 {
  char *ptr;
  ptr=(char*)malloc(10*sizeof(char));
  strcpy(ptr,"data structure");
  printf("\n *ptr=%s \n add=%u",ptr,ptr);
  free(ptr);
  printf("\n *ptr=%s \n add=%u",ptr,ptr);
  getch();
 }

In the above program, even after freeing ptr, the value of ptr and address of ptr is showing correctly.

Please tell the solution & reason behind this problem. Thanks KB

3 Answers3

2

After freeing the memory also the pointer still points to the same memory location. It is called Dangling Pointer.

To avoid dangling pointer, Make pointer to null after free-

free(ptr);
ptr = NULL; // Fix
printf("\n *ptr=%s \n add=%u",ptr,ptr);
Sathish
  • 3,740
  • 1
  • 17
  • 28
2

free() does not reset the pointer back to NULL. It is your responsibility to ensure that you don't dereference it after it's been freed.

If you do, that's undefined behaviour.

I can see two cases on undefined behaviour in your program:

1 - here you are writing past the allocated memory:

 strcpy(ptr,"data structure"); /* UNDEFINED BEHAVIOUR */

2 - here you are dereferencing ptr after it's been deallocated:

free(ptr);
printf("\n *ptr=%s \n add=%u",ptr,ptr); /* UNDEFINED BEHAVIOUR */
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

free does not alter the value in the pointer so the address before and after free will always be the same. You need to set it to NULL explicitly if this is what you want.

The data in the pointed address may or may not change between free and printf. This behaviour is undefined and accessing a dangling pointer is wrong.

Also, you are not allocating sufficient space to store the string you are copying, this is wrong. You should allocate strlen("data structure") + 1 bytes.

Also, do not cast the return value of malloc, p = malloc(....) is the right way to do it with newer compilers.

perreal
  • 94,503
  • 21
  • 155
  • 181