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

后端 未结 4 1525
天命终不由人
天命终不由人 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 11:00

    Without repeating the other answers, it is incumbent on you to null pointers once you have called free(). Calling free() twice on the same allocation will result in heap corruption.

    SomeTypePtr my_type;
    my_type = malloc(sizeof(someType));
    
    /* do stuff */
    
    free(my_type);
    my_type = 0; // Throw away the pointer to released memory, so cannot either free it or use it in any way.
    
    /* do a bunch of more stuff */
    
    free(my_type); // OK now - calling free(0) is safe.
    

提交回复
热议问题