Freeing memory twice

2019-03-10 20:33发布

问题:

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?

回答1:

int *p = malloc(sizeof(int));
//value of p is now lets say 0x12345678

*p = 2;
free(p); //memory pointer is freed, but still value of p is 0x12345678
         //now, if you free again, you get a crash or undefined behavior.

So, after free ing the first time, you should do p = NULL , so if (by any chance), free(p) is called again, nothing will happen.

Here is why freeing memory twice is undefined: Why free crashes when called twice



回答2:

Freeing memory does not set the pointer to null. The pointer remains pointing to the memory it used to own, but which has now had ownership transferred back to the heap manager.

The heap manager may have since reallocated the memory your stale pointer is pointing to.

Freeing it again is not the same as saying free(NULL), and will result in undefined behavior.



回答3:

This is undefined behavior, that can result in heap corruption or other severe consequences.

free() for a null pointer simply checks the pointer value inside and returns. That check will not help against freeing a block twice.

Here's what happens usually. The heap implementation gets the address and tries to "take ownership" of the block at that address by modifying its own service data. Depending on the heap implementation anything can happen. Maybe it works and nothing happens, maybe the service data is corrupted and you've got heap corruption.

So don't do it. It's undefined behavior. Whatever bad things can happen.



回答4:

Yes, "undefined behavior" which almost always results in a crash. (while "undefined behavior" by definition means "anything", various types of errors often behave in quite predictable ways. In case of free(), the behavior is invariably segfault or respective "memory protection error" characteristic to the OS.)

Same if you free() a pointer to anything else than NULL or something you malloc'd.

char x; char* p=&x; free(p); // crash.



回答5:

To avoid free twice i alway using MACRO for free memory:

#ifdef FREEIF
# undef FREEIF
#endif
#define FREEIF( _p )  \
if( _p )              \
{                     \
        free( _p );   \
        _p = NULL;    \
}

this macro set p = NULL to avoid dangling pointer.



回答6:

When you call free on a pointer, your pointer will not get set to NULL. The free space is only given back to a pool to be available for allocation again. Here an example to test:

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

int main(){
    int* ptr = (int*)malloc(sizeof(int));
    printf("Address before free: %p\n", ptr);
    free(ptr);
    printf("Address after free: %p\n", ptr);
    return 0;
}

This program outputs for me:

Address before free: 0x950a008
Address after free: 0x950a008

and you can see, that free did nothing to the pointer, but only told the system that the memory is available for reuse.



回答7:

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.



回答8:

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.`



回答9:

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