I'm rewriting a custom malloc and I would like to be able to throw a glibc error when double free or corruption instead of a classic SegFault. Would that be possible?
*** glibc detected *** a.out: double free or corruption (fasttop): 0x0804b048 ***
======= Backtrace: =========
/lib/libc.so.6(+0x6ff0b)[0xb74baf0b]
/usr/local/gcc/gcc-cilk/lib/libstdc++.so.6(_ZdlPv+0x1f)[0xb7671b4f]
/usr/local/gcc/gcc-cilk/lib/libstdc++.so.6(_ZdaPv+0x1b)[0xb7671b9b]
a.out[0x8048983]
a.out[0x8048b12]
a.out[0x80487d7]
ffffe000-fffff000 r-xp 00000000 00:00 0 [vdso]
Aborted
I don't think it can be easily done, because when calling free() twice no exception is thrown - like in the case of trying to allocate memory and the alloc fails - it's rather undefined behavior. Check out this post for more details.
What you could do is implements your own mechanism for keeping track of the allocated/deallocated memory - sort of like how smart pointers work. Only you would be specifically trying to identify when memory is being deallocated twice.
I think that you have to do your own backtrace/error messages and display it on the error output.
You should also look at abort(3).
If you want to throw yourself the error instead of a segfault you have to check what are the possibilities to do a segfault and then return the message that you want. You can catch it and redirect it in a function that will do some check.
You can check for example if the memory is already free.
How have you done your custom malloc ? brk and sbrk ?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.