free() unexpected behaviour

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kranthi kumar Adari
    New Member
    • Oct 2006
    • 1

    free() unexpected behaviour

    Hi,

    After deallocating dynamically allocated memory, I was still accessible to access the data present in that memory. Can u please help me out why this is happening. This happened with c++(new and delete) operators as well. What is the logic behind. Here is the program I tested in C.

    #include<stdio. h>
    #include<stdlib .h>
    #include<string .h>

    int main()
    {

    char *ptr;
    char *str="kranthi";
    int len;

    len=strlen(str) ;
    ptr=(char *)malloc(len+1) ;

    if(ptr==NULL)
    printf("memory allocation failed");
    else
    {
    strcpy(ptr, str);
    printf("data is %s \n",ptr);
    }

    free(ptr);
    printf("\n after freeing the memory ");
    printf("data is %s \n",ptr);
    return 0;

    }
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Originally posted by kranthi kumar Adari
    After deallocating dynamically allocated memory, I was still accessible to access the data present in that memory. Can u please help me out why this is happening. This happened with c++(new and delete) operators as well. What is the logic behind. Here is the program I tested in C.
    The real question is what are you doing trying to access memory you have deallocated. When you free (or delete) memory all you are doing is informing the underlying system that you are no longer using that memory and that it now has control of that memory and is free to do whatever it wants with it.

    It is possible that just at that moment what the system decides to doing with that memory is nothing.

    However by accessing that memory after freeing it you have invoked undefined behaviour and the system is at liberty to do anything it wishes. All bets are off from this point, you program may or may not work.

    Comment

    • dtimes6
      New Member
      • Oct 2006
      • 73

      #3
      This is because of free returns the memory, but the data at the time is not cleared. It will change until the piece of memory is re-allocated, and used. That is why you have to give a initial number before using your variable. but the memory may returned to system and its not a good idea if you access it again.

      Some of the C++ new and delete operation just call malloc and free.

      Comment

      Working...