Tweet
Get interesting code ideas from me on twitter Follow @virup
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
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.
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!
Implementation:
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#define INUSE 1 | |
#define FREED 0 | |
void *safe_malloc(unsigned int length) | |
{ | |
int *tag; | |
char *actualStartPt; | |
void *data = calloc(length + 4,1); | |
// If no memory | |
if(data == NULL) | |
return NULL; | |
// Put value in dog-tag | |
tag = (int*)data; | |
tag = INUSE; | |
actualStartPt = (char*)data + 4; | |
return (void *)actualStartPt; | |
} | |
unsigned int safe_free(void *data) | |
{ | |
int *tag = (int*)data; | |
tag = tag - 1; | |
if(*tag == FREED) | |
return 0; | |
if(*tag == INUSE) | |
{ | |
*tag = FREED; | |
void *startingPoint = tag; | |
free(startingPoint); | |
return 1; | |
} | |
return 0; | |
} | |
int main() | |
{ | |
// Allocate memory using safe_malloc | |
char *temp = (char *)safe_malloc(10); | |
// Perform tasks with the *temp pointer | |
// ... | |
// ..... | |
// Perform safe free'ing of memory | |
safe_free(temp); | |
// Does not create corruption | |
safe_free(temp); | |
return 0; | |
} |
Get interesting code ideas from me on twitter Follow @virup
No comments:
Post a Comment