malloc double free behaviour

前端 未结 5 722
甜味超标
甜味超标 2020-12-21 14:19

The GNU manual page for malloc defines that when free() called twice with the same pointer (that was previously allocated by malloc())

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-21 14:26

    you can not free twice the same pointer at the same time.

    If you want to do a such behaviour without undefined behaviour.

    you can use the following macro instead of the all free of your code

    #define FREE(X) free(X); X=NULL
    
    
    char *p;
    p=malloc(50);
    FREE(p);
    FREE(p);
    

    When you force the pointer to be NULL, this will avoid the undefined behaviour in the next free. Because free(NULL) do not cause undefined behaviour.

提交回复
热议问题