In Linux environment, when getting "glibc detected *** free(): invalid pointer" errors, how do I identify which line of code is causing it?
Is there a way to force an abort? I recall there being an ENV var to control this?
How to set a breakpoint in gdb for the glibc error?
I believe if you setenv MALLOC_CHECK_
to 2, glibc will call abort()
when it detects the "free(): invalid pointer" error. Note the trailing underscore in the name of the environment variable.
If MALLOC_CHECK_
is 1 glibc will print "free(): invalid pointer" (and similar printfs for other errors). If MALLOC_CHECK_
is 0, glibc will silently ignore such errors and simply return. If MALLOC_CHECK_
is 3 glibc will print the message and then call abort()
. I.e. its a bitmask.
You can also call mallopt(M_CHECK_ACTION, arg)
with an argument of 0-3, and get the same result as with MALLOC_CHECK_
.
Since you're seeing the "free(): invalid pointer" message I think you must already be setting MALLOC_CHECK_
or calling mallopt()
. By default glibc does not print those messages.
As for how to debug it, installing a handler for SIGABRT
is probably the best way to proceed. You can set a breakpoint in your handler or deliberately trigger a core dump.
I recommend you get valgrind:
valgrind --tool=memcheck --leak-check=full ./a.out
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With