This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Is it possible to detect the memory status ?


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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]