Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
113 views
Welcome To Ask or Share your Answers For Others

1 Answer

If it did, you would have to pass a pointer to a pointer to the function:

int * p = malloc( sizeof( int ));
free( & p );

which I'm sure many people would get wrong.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...