What happens when you try to free() already freed memory in c?

后端 未结 14 1033
天命终不由人
天命终不由人 2020-12-09 08:19

For example:

char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE);
free(myString);
free(myString);

Are there any adverse side effects

相关标签:
14条回答
  • 2020-12-09 08:23

    The admittedly strange macro below is a useful drop-in replacement for wiping out a few classes of security vulnerabilities as well as aid debugging since accesses to free()'d regions are more likely to segfault instead of silently corrupting memory.

    #define my_free(x) do { free(x); x = NULL; } while (0)
    

    The do-while loop is to help surrounding code more easily digest the multiple-statements. e.g. if (done) my_free(x);

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

    In short: "Undefined Behavior".

    (Now, what that can include and why that is the case the others have already said. I just though it was worth mentioning the term here as it is quite common).

    0 讨论(0)
  • 2020-12-09 08:28

    Depending on which system you run it on, nothing will happen, the program will crash, memory will be corrupted, or any other number of interesting effects.

    0 讨论(0)
  • 2020-12-09 08:28

    Always set a pointer to NULL after freeing it. It is safe to attempt to free a null pointer.

    It's worth writing your own free wrapper to do this automatically.

    0 讨论(0)
  • 2020-12-09 08:28

    It (potentially) makes demons fly out of your nose.

    0 讨论(0)
  • 2020-12-09 08:30

    One of nothing, silent memory corruption, or segmentation fault.

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