3 ms·
The free one at least will be detected immediately with a good libc, but nice idea. It gives me another idea though: #define free(x) do { free(x); x = NUL
by tedunangst 15y ago
The free one at least will be detected immediately with a good libc, but nice idea. It gives me another idea though:
#define free(x) do { free(x); x = NULL; } while (0)
Assuming you can turn it off just before shipping, this will hide many forms of double free during development which then show up when the evil line is deleted.
- 1amzave 15y agoThat assumes 'x' is an lvalue, which it may very well not be (thus causing compilation errors, which would presumably get caught pretty quickly).
- tedunangst 15y agoI'm having a very hard time thinking of an example where you'd free an rvalue. Function return, maybe, but without using the value? It (almost) had to be an lvalue in order to get the malloc into it. Ah, an unconst cast. free((void *)constx), but lots of compilers don't catch that. Is there something else you were thinking of? There's also people doing stupid shit like free(&x), but those people don't need evil macros to dick up their code. :)
- copper 15y agoFunction calls seem right - particularly if they're badly written. Also, this macro might give curious results when passed in ptr++ . While this is C++, I've actually seen this particular construct: delete new SomeClass(...); used as, basically, an eye-poppingly clever way of initializing something, doing work, and then cleaning up after.
- tedunangst 15y ago{ SomeClass makeitso; } :) Also, free(ptr++) is broken by design, the post increment value is useless. But free(*ptr++) is a good case.
- copper 15y ago> free(*ptr++) Yes, of course - that's what I thought I'd written. Clearly not :)
- SamReidHughes 15y agoI can think of one case in a project where we allocate a 4K block, fill the first n bytes with header info, and then add n bytes to the pointer and return it to something that's told it's getting a 4K - n byte block. And then later it passes that return value to some function that deallocates the block, by calling free(((char *)p) - n).