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

后端 未结 14 1035
天命终不由人
天命终不由人 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:30

    Yes, you can get a double free error that causes your program to crash. It has to do with malloc's internal data structures to keep track of allocated memory.

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

    It may crash your program, corrupt memory, or have other more subtle negative effects. After you delete memory, it is a good idea to set it to NULL (0). Trying to free a null pointer does nothing, and is guaranteed to be safe. The same holds true for delete in c++.

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

    Don't do that. If the memory that got freed is re-allocated to something else between the calls to free, then things will get messed up.

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

    Answer summary:

    Yes, bad things can and probably will happen.

    To prevent this do:

    free(myString);
    myString = NULL;
    

    Note that all references to the memory must be set to NULL if others were created.

    Also, calling free() with a NULL results in no action. For more info see: man free

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

    Bad Things (TM)

    Really, I think it's undefined so anything at all including playing "Global Thermonuclear War" with NORAD's mainframe

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

    Another interesting situation:

    char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE);
    char * yourString = myString;
    
    if (myString)
    {
        free(myString);
        myString = NULL;
    }
    // Now this one is safe, because we keep to the rule for 
    // setting pointers to NULL after deletion ...
    if (myString)
    {
        free(myString);
        myString = NULL;
    }
    
    // But what about this one:
    if (yourString)
    {
        free(yourString);
        yourString = NULL;
    }
    
    //?!? :)
    
    0 讨论(0)
提交回复
热议问题