Freeing malloced structure in a function

后端 未结 4 1421
一生所求
一生所求 2020-12-21 03:42

I\'m creating a source files containing buffer functionality that I want to use for my other library that I\'m creating.

It is working correctly but I\'m having tro

相关标签:
4条回答
  • 2020-12-21 04:14

    Once you've called free() on the allocated pointer, attempt to make use of the pointer invokes undefined behavior. You should not be doing that.

    To quote C11 standard, chapter §7.22.3.4, free() function

    The free() function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. [..]

    It never say's anything about a cleanup, which you might be (wrongly) expecting.

    Just to add clarity, calling free() does not always actually free up the allocated physical memory. It just enables that pointer (memory space) to be allocated again (returning the same pointer, for example) for successive calls to malloc() and family. After calling free(), that pointer is not supposed to be used from your program anymore but C standard does not guarantee of a cleanup of the allocated memory.

    0 讨论(0)
  • 2020-12-21 04:23

    free() call will just mark the memory in heap as available for use. So you still have the pointer pointing to this memory location but it's not available anymore for you. Thus, the next call to malloc() is likely to assign this memory to the new reservation.

    To void this situations normally once you free() the memory allocated to a pointer you should set it to NULL. De-referencing NULL is UB also but at least when debugging you can see tha pointer should not be used because it's not pointing to a valid memory address.

    0 讨论(0)
  • 2020-12-21 04:31

    [too long for a comment]

    To allow your "destructor" to set the pointer passed to NULL modify your code like this:

    void dbuffer_destroy(DBUFF ** buffer)
    {
      if ((NULL == buffer) || (NULL == *buffer))
      {
         return;
      }
    
      free((*buffer)->pPosition);
      free((*buffer)->pStorage);
      free(*buffer);
      *buffer = NULL;
    }
    

    and call it like this:

      ...
      dbuffer_destroy(&buff);
      ...
    
    0 讨论(0)
  • 2020-12-21 04:35

    If any attempt is made to read memory that has been freed can crash your program. Or they might not. As far as the language is concerned, its undefined behaviour.

    Your compiler won't warn you about it(or stop you from accessing it). But clearly don't do this after calling free -

    printf("buff total size: %d\n", buff->total_size);
    

    As a good practice you can set the freed pointer to NULL .

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