Monday, October 1, 2012

Use of Dog-tag Fields to Check for Corrupted Memory

Often times in a program, memory needs to be allocated and subsequently deleted. A program might be fatally affected if a deleted memory is reused, or if a memory is deleted more than once. "Dog-tag" fields are used to detect corruption. A tag field is attached to memory structure for error checking and if the tag does not have the expected value, then the data is corrupted.

Lets say you want to request 10 bytes. We will use a tag field of 4 bytes. It works in the following manner:

1. Allocate a total of 10 + 4 = 14 bytes

2. Set the first 4 bytes to a tag value.  For our purpose, we will assume INUSE tag equal to 1. Any other value indicates corruption.

3. Return a pointer to the memory which starts AFTER the tag field


When deleting, follow these steps:

1. Check the tag. If the tag value is equal to INUSE, then set it to FREED (assumed to be 0 in our case).

2. Delete the whole 14 bytes

That's it!


The following code is an implementation of the above concept in C. It has two function: safe_malloc() and safe_delete() which when used in pair performs the above strategy.

Get interesting code ideas from me on twitter

No comments: