4 ms·
free() could be wrapped in a macro, but it would not catch the case where multiple copies of the pointer is stored. #define my_free(x) { free(x); (x) = NULL; }
by nroets 7y ago
free() could be wrapped in a macro, but it would not catch the case where multiple copies of the pointer is stored.
#define my_free(x) { free(x); (x) = NULL; }
Note that the extra assignment will often be optimized away because
(a) the pointer is assigned to a malloc() after the call to my_free() OR
(b) the pointer goes out of scope e.g. is popped off the stack.
- simias 7y agoI guess it's better than nothing but that won't work if x is some temporary local variable instead of the long term storage location. It also won't help much if there are several pointers to the resource. As such I wonder if a macro is better that just explicitly nulling the pointer after free, at least there's no obfuscation of what's going on. Generally I agree with you though, setting pointers to NULL after free is good practice and probably worth enforcing in the coding style.
- bluecalm 7y agoWell, if there are several pointers to the same memory you need some kind of logic to handle the number anyway. I don't think using free is a good idea in such cases. You need a wrapper which checks for the counter and then decreases it and frees on zero.