2 ms·
> only the resources that were allocated How does it know which were allocated and which were not? If you are talking about memory allocation, then you could s
by zabzonk 5y ago
> only the resources that were allocated
How does it know which were allocated and which were not? If you are talking about memory allocation, then you could simply deallocate all the pointers provided they were initially set to NULL. Freeing a NULL pointer is well-defined in C.
- maccard 5y agoFiles, sockets, mutexes are all examples of resources that aren't memory. Someone posted an example in this comment thread - [0]. [0] https://wiki.sei.cmu.edu/confluence/display/c/MEM12-C.+Consider+using+a+goto+chain+when+leaving+a+function+on+error+when+using+and+releasing+resources https://wiki.sei.cmu.edu/confluence/display/c/MEM12-C.+Consi...
- zabzonk 5y ago> Files, sockets, mutexes are all examples of resources that aren't memory I know - that's why I explicitly mentioned memory.
- ahartmetz 5y agoThe information is in the instruction pointer. You jump to the place that deallocates the last resource that was allocated, followed by the second-to-last etc. Also, free(NULL) is not well-defined in C, and other resource types aren't so easy to check. delete nullptr in C++ is well-defined, but you rarely need it.
- zabzonk 5y ago> free(NULL) is not well-defined in C Oh yes it is: https://stackoverflow.com/questions/1938735/does-freeptr-where-ptr-is-null-corrupt-memory https://stackoverflow.com/questions/1938735/does-freeptr-whe...
- ahartmetz 5y agoI stand corrected. So, these days, null checks before free() are just for compatibility with very old systems, or more likely "tradition". I wonder where I got my wrong information? I have even seen null checks before delete in C++ code recently written by C programmers :o
- wott 5y agoWhen it is in the normal execution path, the test avoids a function call, so there's a little bit of performance gain. It can also be a bit self-documenting, or be a place-holder if there is for example stuff to delete in a loop (elements of an array) before releasing the pointer itself (the array). I don't know, when you read it, sometimes it feels natural and meaningful, and sometimes you know that the author didn't know that free() handles NULL all right.