问题
The GNU manual page for malloc
defines that when free()
called twice with the same pointer (that was previously allocated by malloc()
) "undefined behaviour occurs".
What kind of behaviour is that?
Where can I find more Information about this kind of error?
回答1:
"Undefined behavior" simply means that the implementation isn't required to deal with the situation in any particular way; any behavior or result is considered "correct".
The result of free
-ing a pointer more than once is up to the underlying implementation of malloc
; the result could be a crash and core dump, or it could corrupt the malloc
arena (fouling up future allocations/deallocations), or it could ignore the double free
entirely.
回答2:
The C99 standard states the following for undefined behaviour (under the Terms and definitions section):
Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
In summary: anything can happen. The worst case is for the program to behave as expected.
回答3:
you can not free twice the same pointer at the same time.
If you want to do a such behaviour without undefined behaviour.
you can use the following macro instead of the all free of your code
#define FREE(X) free(X); X=NULL
char *p;
p=malloc(50);
FREE(p);
FREE(p);
When you force the pointer to be NULL
, this will avoid the undefined behaviour in the next free. Because free(NULL)
do not cause undefined behaviour.
回答4:
Undefined behaviour means that anything can happen. One of the possible outcomes is that your program runs perfectly. Another possible outcome is that your program crashes. Or indeed anything else that you can think of.
You won't gain any insight trying to analyse particular instance of undefined behaviour. The remedy is not to call free()
twice.
回答5:
"undefined behavior" generally means your program will crash. For implementors of the c library it means they can handle that case however they want. They would be free for example to ignore your second invalid free. Almost no c libraries will do this. Most c libs will just abort your program with some kind of memory violation error.
来源:https://stackoverflow.com/questions/13685240/malloc-double-free-behaviour