How to test heap in case of using malloc(), etc.?

Tip / Sign in to post questions, reply, level up, and achieve exciting badges. Know more

cross mob
RaAl_264636
Level 6
Level 6
50 sign-ins 25 sign-ins 10 solutions authored

Hi,

anyone knows a good and bullet-proof way to test heap consistency in case of using malloc(), etc.? I'm working on a queue implementation which is able to dynamically resize its data (not linked list approach). So, there's a queue struct, which has a pointer for the data field assigned by malloc(). The queue itself is also created dynamically.

On a first thought, I'd reserve almost the complete heap by malloc(), fill it with a bit pattern of e.g. 0x55, then release it and create the queue(s). After that, I'd enqueue and dequeue data, with debug output of the queue state and data fields after each operation.

Any other ideas?

Regards,

Ralf

0 Likes
1 Solution

You will use more than your 16 bytes, malloc() will need some room for housekeeping. Changing a byte outside the returned memory area is deadly because it will destroy relevant information. Just like defining an array and perform a write access out of bounds.

Checking algorithm:

Encapsulate malloc() into a routine MyMalloc() which allocates more memory than needed and initializes the extra portion with a given pattern.

Encapsulate free() into MyFree() that checks the extra part for unchanged and  free()s the originally requested memory.

Bob

View solution in original post

0 Likes
4 Replies
Bob_Marlowe
Level 10
Level 10
First like given 50 questions asked 10 questions asked

I do not (yet) understand what you want to test the heap for. malloc() works fine and will return NULL when a request cannot be satisfied.

Bob

0 Likes

Hi Bob,

sorry for the misleading description. Of course malloc() is well implemented. I want to test if my queue implementation handles the memory provided by malloc() correctly. For example, if I have 16 bytes provided by malloc(), how to check that I don't use 17 bytes.

Regards,

Ralf

0 Likes

You will use more than your 16 bytes, malloc() will need some room for housekeeping. Changing a byte outside the returned memory area is deadly because it will destroy relevant information. Just like defining an array and perform a write access out of bounds.

Checking algorithm:

Encapsulate malloc() into a routine MyMalloc() which allocates more memory than needed and initializes the extra portion with a given pattern.

Encapsulate free() into MyFree() that checks the extra part for unchanged and  free()s the originally requested memory.

Bob

0 Likes

Hi Bob,

okay, that algorithm goes into the same direction as my approach. I think this can be done for the debug build, using the defined DEBUG symbol. For the release build, the original malloc() and free() functions can be used. Good hint, I'll try that.

Regards,

Ralf

0 Likes