Using realloc (X, 0) instead of free() and using malloc with length of a string +1

前端 未结 6 1734
难免孤独
难免孤独 2020-12-10 06:52

So I don\'t really know how to put the title this time. First of all I\'d like to say that I\'ve seen several comments on this page about warning if the question is related

6条回答
  •  佛祖请我去吃肉
    2020-12-10 07:28

    If you hope to maintain compatibility, realloc(p,0) is never equivalent to free(p), and zero allocations without subsequent frees are memory leaks plain and simple, even on Linux.

    /* leak.c */
    #include 
    #include 
    int main(int argc, char* argv[]) {
        void* p;
        mtrace();
        p = malloc(0x100);
        p = realloc(p, 0);
        exit(EXIT_SUCCESS);
    }
    
    $ cc -g leak.c -o leak
    $ export MALLOC_TRACE=/tmp/t
    $ ./leak
    $ mtrace ./leak $MALLOC_TRACE
    

提交回复
热议问题