freeing a null pointer

后端 未结 7 997
天涯浪人
天涯浪人 2020-12-09 14:52

What happens inside memory if we try to free a pointer which is pointing to NULL? Is that ever valid?

Why does it not show any warning/error messages?

相关标签:
7条回答
  • 2020-12-09 15:11

    I'd go for:

    #ifdef MY_DOUBTS_HAUNT_ME_IN_MY_DREAMS
        #define safe_free(x) do { if ((x)) free((x)); } while(0)
    #elseif /* feeling gutsy */
        #define safe_free(x) free((x))
    #endif
    

    ;-||

    0 讨论(0)
  • 2020-12-09 15:16

    From C99 section 7.20.3.2 : The free function

    Synopsis

     1 #include <stdlib.h>
       void free(void *ptr);
    

    Description

    2 The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.

    0 讨论(0)
  • 2020-12-09 15:16

    It might be safe (I didn't know that, but the other answers seem to suggest that), but I won't fall into the habit of not caring about whether the pointer is already null. The assignment p = NULL; after every free soon follows as a corollary. This is dangerous in multithreaded applications, as after this assignment, p might be used by another thread and would be freed again by the current thread while it is expected to be alive by the other threads.

    Every malloc'd memory should be freed once. Period.

    0 讨论(0)
  • 2020-12-09 15:18

    What happens inside memory if we try to free a pointer which is pointing to NULL. is that ever valid?

    Nothing.

    why does it not show any warning/error messages?

    First, the behaviour is valid by definition, so no error or warning needs to be issued.

    Second, a pointer is pointing to NULL at runtime. How should a warning or error message be displayed, if at all? Imagine that you are playing a game called Kill the Zombie and while two of these beings are attacking you, a popup error message appears, saying: "Warning, NULL pointer freed."

    0 讨论(0)
  • 2020-12-09 15:23

    From http://linux.die.net/man/3/malloc:

    If ptr is NULL, no operation is performed.

    0 讨论(0)
  • 2020-12-09 15:24

    freeing null pointer will have no effect in the execution .

    0 讨论(0)
提交回复
热议问题