Is there any harm in calling 'free' for the same pointer twice in a C program?

后端 未结 4 1529
天命终不由人
天命终不由人 2021-01-04 10:44

If I have a c program, like:

SomeTypePtr my_type;
my_type = malloc(sizeof(someType));

/* do stuff */

free(my_type);

/* do a bunch of more stuff */

free(m         


        
4条回答
  •  心在旅途
    2021-01-04 10:54

    Deallocating a memory area with free does not make the contents of the pointer NULL. Suppose that you have int *a = malloc (sizeof (int)) and a has 0xdeadbeef and you execute free (a) then after execution a still contains 0xdeadbeef but after the free call this memory address is no more reserved for you. Something like you have rented a flat with malloc used for some time, returned the flat by free then you might have a duplicate key for the flat, but it is not reserved for you.

    Doing a free on an already freed memory will result in double free memory corruption.

提交回复
热议问题