Reputation: 2494
I've been seeing quite a bit of erroneous code around the web and in my Advanced C class (such as the code below). While I understand that it's obviously bad coding practice, I'm having a difficult time as to what it does that's so bad other than waste CPU cycles. From my understanding so far, if a pointer allocation is not located in the "malloc table" (for lack of a better word), it is usually ignored. I'd appreciate if someone here could provide me with a better understanding as to why this is bad and (other than the fact that it's a silly thing to do) and the consequences of it are.
char* ptr = malloc(1);
...
free(ptr);
...
free(ptr);
Upvotes: 7
Views: 6453
Reputation: 2096
A good advise: nullify pointer after free. In your case you have undefined behaviour, because computer can allocate memory, which is pointed by ptr, or may not allocate this piece of memory, or this chunk of memory could be added to other chunk of memory during defragmentation, etc.
On the other hand, free(NULL) is defined and will do nothing.
char* ptr = malloc(1);
...
free(ptr);
ptr = NULL;
...
free(ptr);
Upvotes: 5
Reputation: 743
Consider in your example after free(ptr) you did following
char* ptr = malloc(1);
free(ptr) // <-- This will delete the pointer
ptr2 = malloc(1) // <-- now you request again
now malloc is what it is and can return the same pointer as ptr and if it does and if now you do
// if you call me again and if ptr2 == ptr oops!
free(ptr)
-- your ptr2 is freed causing unexpected behavior with lots of crash, pain and hours of debugging..
Upvotes: 16
Reputation: 106012
C11, section 7.22.3.3 says that:
[...] Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to
free
orrealloc
, the behavior is undefined.
Upvotes: 7
Reputation: 500257
This is not just a waste of CPU cycles. Double free()
is undefined behaviour, which means that the program is allowed to behave in arbitrary ways.
The program might work just fine, or it might blow up in testing, or it might pass all your tests and then blow up in your customer's face, or it might corrupt some data, or it might launch a nuclear strike, etc. All of these are valid manifestations of undefined behaviour.
Upvotes: 7