开发者

Can a call to free() in C ever fail?

开发者 https://www.devze.com 2023-02-17 01:16 出处:网络
Can a call to free() fail 开发者_如何学Goin any way? For example: free(NULL); Freeing a NULL pointer cannot fail. And free doesn\'t return any error, but freeing unallocated memory, already freed m

Can a call to free() fail 开发者_如何学Goin any way?

For example:

free(NULL);


Freeing a NULL pointer cannot fail. And free doesn't return any error, but freeing unallocated memory, already freed memory or the middle of an allocated block is undefined behaviour - it may cause a memory error and the program may abort (or worse, it will corrupt the heap structure and crash later).

Or, even worse than that, keep running but totally corrupt your data and write it to disk without you realising :-)

The relevant portion of the standard (C99) is section 7.20.3.2:

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

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. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

The free function returns no value.


Unless you invoke undefined behavior (like "double-free" or try to free() a string literal) free() can't fail.


free(NULL) does nothing; free on a pointer that wasn't allocated with the same allocator (malloc, calloc, etc.) or was already freed is undefined. Since free returns void, the only way it can fail is by crashing (e.g. segfault).


Yes it can fail in multiple situations. E.g.

  1. You free something that was not allocated dynamically E.g. variables on stack
  2. You allocate a pointer and try to free pointer + 1


free(NULL);

Calling free() with a null pointer is permitted and will not cause an error - See: free() - Opengroup

Calling free with a previously free'd pointer will usually cause a segment violation and your program to be terminated.


Depending on the implementation, free() could fail if there is memory corruption, such as with this:

char *p = malloc(1000);
*(p-1)=7;
free(p);

Although that is a contrived example, similar things can happen by running off the end or start of an array. The first you may know of it is a protection fault in free().

0

精彩评论

暂无评论...
验证码 换一张
取 消