Freeing memory twice

2019-03-10 21:03发布

In C and C++, Freeing a NULL pointer will result in nothing done.

Still, I see people saying that memory corruption can occur if you "free memory twice".

Is this true? What is going on under the hood when you free memory twice?

9条回答
欢心
2楼-- · 2019-03-10 21:36

free() frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is NULL, no operation is performed.

So, you get undefined behavior, and anything could happen.

查看更多
▲ chillily
3楼-- · 2019-03-10 21:36

1) Handling of dynamic memory is not done by compiler. There are run-time libraries which take care of this. For eg. : glibc provides APIs like malloc and free, which internally make system calls(sys_brk) to handle the heap area.

2) Freeing same memory twice refers to a condition like this : Suppose you have char *cptr;

You allocate memory using : cptr = (char *) malloc (SIZE);

Now, when you no longer need this memory, you can free it using this : free(cptr);

Now here what happens is the memory pointed to by cptr is free for use.

Suppose at a later point of time in the program you again call a free(cptr), then this is not a valid condition. This scenario where you are freeing the same memory twice is know as "freeing a memory twice" problem.`

查看更多
够拽才男人
4楼-- · 2019-03-10 21:38

Freeing memory more than once can have bad consequences. You can run this piece of code to see what may happen for your computer.

#include <stdio.h>      /* printf, scanf, NULL */
#include <stdlib.h>     /* malloc, free, rand */

int main ()


  {
  int i,n;
  char * buffer;

  printf ("How long do you want the string? ");
  scanf ("%d", &i);

  buffer = (char*) malloc (i+1);
  if (buffer==NULL) exit (1);

  for (n=0; n<i; n++)
          buffer[n]=rand()%26+'a';
  buffer[i]='\0';

  printf ("Random string: %s\n",buffer);
  free (buffer);
  free (buffer);

  return 0;
}

Many standard libraries like CSparse use a wrapper function that handles memory issues. I copied the function here:

 /* wrapper for free */
    void *cs_free (void *p)
    {
        if (p) free (p) ;       /* free p if it is not already NULL */
        return (NULL) ;         /* return NULL to simplify the use of    

    }

This function can handle the issues with memory. Please note that you have to take care of the condition that malloc returns NULL in some cases

查看更多
登录 后发表回答