Freeing malloced structure in a function

纵饮孤独 提交于 2019-11-29 14:28:50

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.

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 .

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.

[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);
  ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!