Define a buffer allocated using malloc ()

Is there a way to determine if a buffer has been allocated to 'malloc'? as a function with the following signature:

bool is_malloced(void *buf); 

Is there such a mechanism in posix?

+4
source share
3 answers

Nope. Neither C11 nor POSIX provide such a mechanism.

+2
source

mmm, if you are a serious person, you really can:

 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, such a thing is insanity, but really you can.

+1
source

One easy way to emulate such a function is to wrap malloc() in a user-defined function that:

  • allocates a buffer which is for example 4 bytes larger
  • stores some magic number (32 bits) at the beginning of the selected block
  • increments a pointer by 4 bytes before returning it to the caller

Given the pointer, you can check if there is a malloc 'ed by looking for a magic number.

Of course, this is not ideal:

  • the magic number may be there by accident. This can help set it to null in a wrapped free() call. XOR-ing with a pointer, etc. It can also make it more reliable. However, this is a heuristic.
  • on memory-protected architectures, you can cause a page error when checking for a pointer that was not malloc'ed.

With all the flaws, this is still a useful method, I used it several times when debugging memory corruption on embedded systems.

If we are going to replace malloc() with some shell, we could also build a linked list of allocated blocks. It is much more reliable, but also more difficult.

0
source

Source: https://habr.com/ru/post/1441646/


All Articles