Skip to content

Instantly share code, notes, and snippets.

@xixitalk
Last active July 10, 2016 09:36
Show Gist options
  • Save xixitalk/d9364ee670f09f0365fd45466a773ba4 to your computer and use it in GitHub Desktop.
Save xixitalk/d9364ee670f09f0365fd45466a773ba4 to your computer and use it in GitHub Desktop.
malloc封装用于检测内存越界
#define BEGIN_MAGIC 0x3a3a3a3a
#define END_MAGIC 0x5a5a5a5a
void *mymalloc(unsigned int size)
{
char *ptr = (char *)malloc(size+12);
unsigned int *ptmp = NULL;
if(NULL == ptr)
return NULL;
memset(ptr,0,size+12);
ptmp = (unsigned int *)ptr;
*ptmp = size;
ptmp = (unsigned int *)(ptr + 4);
*ptmp = BEGIN_MAGIC;
ptmp = (unsigned int *)(ptr + size + 8);
*ptmp = END_MAGIC;
return (void*)(ptr+8);
}
void mymemcheck(void *ptr)
{
unsigned int *ptmp = NULL;
char *ptr2 = (char *)((unsigned int)ptr - 8);
unsigned int size = 0;
ptmp = (unsigned int *)(ptr2);
size = *ptmp;
ptmp = (unsigned int *)(ptr2+4);
assert(BEGIN_MAGIC == *ptmp);
ptmp = (unsigned int *)(ptr2 + size + 8);
assert(END_MAGIC == *ptmp);
}
void myfree(void *ptr)
{
char *ptr2 = (char *)((unsigned int)ptr - 8);
mymemcheck(ptr);
free(ptr2);
}
用户thread函数
void *ptr = mymalloc(BUFFER_SIZE);
while(1)
{
mymemcheck(ptr);
/*do something*/
mymemcheck(ptr);
/*do something more*/
}
myfree(ptr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment