3 ms·
You could potentially write the "free" function like this: static inline void free(void *ptr) { if (!ptr) return; _free(ptr
by JoshTriplett 11y ago
You could potentially write the "free" function like this:
static inline void free(void *ptr)
{
if (!ptr)
return;
_free(ptr);
}
Then the compiler can easily inline this, omit the NULL check if it knows the pointer can't be NULL, or omit the whole thing if it knows the pointer is NULL.
- the_why_of_y 11y agoGCC 5 already does that for you (and more), since malloc/free are C standard library functions: #include <stdlib.h> int main() { free(NULL); char *foo = malloc(42); free(foo); } gcc -O1 compiles it to: 00000000004004f6 <main>: 4004f6: b8 00 00 00 00 mov $0x0,%eax 4004fb: c3 retq 4004fc: 0f 1f 40 00 nopl 0x0(%rax)
- PeCaN 11y agofree(NULL) is already perfectly legal (specced to be a no-op) as noted by the parent. The problem is that `char * s;` is probably _not_ NULL, so you'd try to free some random address on the stack. Of course it is easily fixed with `_cleanup_free char * s = NULL;`, but it's a somewhat difficult error to spot sometimes. EDIT: I super misread that, my bad.
- adrusi 11y agoThe point is that this informs the compiler of that behavior of free so that it can optimize it away. Basically it gives you some of the advantages you'd get if free were a compiler intrinsic (which it might be, idk).