Is there a way to find out if a pointer is okay to pass to free(), other than by calling free()?

StackOverflow https://stackoverflow.com/questions/21963425

  •  15-10-2022
  •  | 
  •  

Question

First, a little background so you won't think I'm attempting to do something insane:

I'm trying to debug a crash in a C library that was written by someone else. The crash looks like this:

TheProgram(44365,0x7fff75996310) malloc: *** error for object 0x7fb8d4b9d440: pointer being freed was not allocated

The crash occurs on a system where I can't run valgrind, alas. The first thing I did was wrap debug-print-macros around all of the library's calls to malloc(), calloc(), realloc(), and free() so that I see printf() output whenever memory is allocated/reallocated/freed by the library. From that debug output, it appears that the pointer that makes free() crashing was indeed allocated previously in the program, and that it wasn't freed before the problem free() call:

JJ_CHECK_MALLOC at [fastgr.c : 265] malloc() returned 0x7fb8d4b9d440
[...]
JJ_CHECK_FREE at [dotinit.c : 204] about to call free(0x7fb8d4b9d440)
TheProgram(44365,0x7fff75996310) malloc: *** error for object 0x7fb8d4b9d440: pointer being freed was not allocated

So presumably what must be happening is that somewhere after the call to malloc() and before the call to free(), the heap must be getting corrupted in such a way that free() no longer thinks that that pointer is valid.

What I need to do, then, is track down the routine that is causing the heap corruption. One way I could do this is to query the validity of the pointer at various places along the execution path, and narrow down where its status changes from "valid heap pointer" to "the heap manager doesn't know what this pointer is". But the only way I know of to find out whether the heap manager thinks the pointer is free-able is to call free(), which I obviously can't do while the program still wants to use the pointer. Is there some way to call the check-if-pointer-is-in-heap function that free() uses, without actually freeing the data?

No correct solution

OTHER TIPS

In general: No.

There are "debugging heaps" which surround allocated blocks with additional "fence" information to help detect bad-pointer errors. These will fairly reliably complain if you try to free something that wasn't allocated through them, since the fences will be missing. (They'll also complain if you've overwritten the end of the buffer and damaged the fence, of course.) In environments where code changed frequently, I've sometimes run with these heaps permanently enabled despite the performance costs... but one would hope that they could normally be turned off before the code ships to customers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top