Any reasons why this can not be standard behavior of free()
?
multiple pointers pointing to the same object:
#include <stdlib.h>
#include <stdio.h>
void safefree(void*& p)
{
free(p); p = NULL;
}
int main()
{
int *p = (int *)malloc(sizeof(int));
*p = 1234;
int*& p2 = p;
printf("p=%p p2=%p
", p, p2);
safefree((void*&)p2);
printf("p=%p p2=%p
", p, p2);
safefree((void*&)p); // safe
return 0;
}
assignment from malloc
demands cast from void*
vice versa:
safefree()
demands cast to void*&
(reference)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…