Is it possible to detect the memory status ?

Sven Eschenberg eschenb@cs.uni-frankfurt.de
Tue Jan 27 21:27:00 GMT 2009


Something I'd like to add:

If you are not worried about performance and for the sake of tidiness, 
you could do the following:
In most cases where you malloc(), you are using data structures etc., 
and usually have a set of functions handling them. The deallocation 
function could first free the mem, then invalidate the pointer. This way 
other functions handling the datastructure can check against this 
'constraint' and avoid accidently creating segfaults by not accessing 
the freed mem.

If you are just curious and have some binary or make use of libs etc. 
and think there might be a leak somewhere, valgrind might be a tool to 
look into your problem.

Regards

-Sven


John (Eljay) Love-Jensen schrieb:
> Hi Mustafa,
> 
>> I am wondering whether it is possible to detect that a memory is already
>> freed or not in a C program.
> 
> Possible?  Yes.  But you'll probably need to write your own heap allocator
> that keeps track of allocated pointers, and use that information in your
> ancillary routine which returns the results of testing if that pointer
> refers to allocated or freed memory.  (I'm not sure what you want to do with
> a pointer that refers to the middle of an allocated block of memory.)
> 
>> If this is not available with the current compilers, is it possible to
>> implement such library functions ?
> 
> Not available "out of the box".  Some third parties may have already written
> such a heap allocation library.  And it is possible to implement such a
> library.
> 
> If you need your custom heap library to be performant... you may want to
> take a look at existing code such as the code in GNU CLib.  Otherwise, it
> can be tricky.
> 
> If you just want your custom heap library to be used for diagnostics to
> detect programmer error... well, it shouldn't be difficult to implement
> non-optimized heap manager.
> 
> If you have all your own source code, you could take a shortcut and do
> something like this:
> 
> #define malloc(x) MyTrackAllocationMalloc(x)
> #define free(x) MyTrackAllocationFree(x)
> 
> That won't catch malloc()'s from other pre-built code, but would be a way to
> instrument your own compiled source with a intercepted malloc/free which
> could perform the additional functionality you are looking for.  (You'd have
> to implement MyTrackAllocationMalloc and MyTrackAllocationFree and probably
> a MyTrackAllocationTest routine.  I leave that as an exercise.)
> 
> HTH,
> --Eljay
> 



More information about the Gcc-help mailing list