4

Is there any way to identify if a buffer was allocated by 'malloc'? like a function with the following signature:

bool is_malloced(void *buf);

Does such a mechanism exist in posix?

Woodrow Douglass
  • 2,605
  • 3
  • 25
  • 41
  • `bool is_malloced(void *buf) { free(buf); return true; }` ;) Seriously, I know of no such thing. – Daniel Fischer Oct 23 '12 at 20:15
  • No, but you could write your own allocator that could support this. But why do you think you need such a function? – TJD Oct 23 '12 at 20:17
  • I actually don't *need* such a function, I was just curious... – Woodrow Douglass Oct 23 '12 at 20:21
  • http://stackoverflow.com/q/276612/1202636 – effeffe Oct 23 '12 at 20:22
  • 1
    Your best bet is to replace `malloc` with your own, using a library preloading mechanism or some other, and wrap the POSIX malloc call in your own implementation, adding flagging a pointer as "malloced" in some sort of a map. The problem is there is no portable way of either overriding malloc (there is `malloc_hook` in GNU C) or linking to another `malloc`. – Armen Michaeli Oct 23 '12 at 20:23
  • @TJD just malloc/free wrapper is enough for that, wrapper functions that will add / remove ptr's to allocated chunks in own dynamic or static table (hash) – pmod Oct 23 '12 at 20:24

3 Answers3

2

Nope. Neither C11 nor POSIX provide any such mechanism.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
1

mmm if you are a serious person, you could actually do:

Hash   *hsh;   /* global hash already initialized. */
void *custom_malloc(size_t size)
{
     void  *ptr;

     ptr = malloc(size);

    hash_add(hsh, ptr);
  return ptr;
}

/* tester */

_Bool malloced(void *ptr)
{
      if(hash_retrieve(hsh, ptr))
           return TRUE;
      return FALSE;
}

of course doing such thing is madness, but indeed you can.

yeyo
  • 2,954
  • 2
  • 29
  • 40
0

One simple way to emulate such a functinality would be to wrap malloc() in a custom function which:

  • allocates a buffer which is e.g. 4 bytes bigger
  • stores some magic number (32 bit) at the beginning of the allocated block
  • increments a pointer by 4 bytes before returning it to the caller

Given a pointer one can check if it is malloc'ed by looking for the magic number.

Of course, it is not perfect:

  • the magic number can be there by accident. Setting it to null in a wrapped free() call can help. XOR-ing it with the pointer, etc. can also make it more reliable. Still, it's a heuristic.
  • on architectures with memory protection you can trigger page fault when checking pointer which was not malloc'ed.

With all the drawbacks, it's still a useful technique, I've used it a few times when debugging some memory corruption in embedded systems.

If we are about to replace malloc() with some wrapper, we could as well build a linked list of allocated blocks. Much more reliable, but also more complex.

Code Painters
  • 7,175
  • 2
  • 31
  • 47