前面学习webkit曾经提过alloc/free校验的问题,当时跳过了,今日看云风大牛的文章<给你的模块设防>,重新想了一下,这种技术,结合gdb简单分析就很明白了,我个人看到的主要是假设有type* ptr,那么ptr+1,取决于type的类型。比如:
struct cookie {
size_t sz;
int tag;
};
那么struct cookie* ptr,ptr+1的地址是&ptr+16,因为sizeof(struct cookie)==16。下面是code和gdb跟踪结果:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define DOGTAG_VALID 0xbadf00d
#define DOGTAG_FREE 0x900dca7e
#define DOGTAG_TAIL 0xd097a90
struct cookie {
size_t sz;
int tag;
};
void *
my_malloc(size_t sz)
{
if (sz == 0)
sz = 1;
struct cookie * c = malloc(sizeof(struct cookie)
+ sz + sizeof(int));
assert(c != NULL);
c->sz = sz;
c->tag = DOGTAG_VALID;
int * tail = (int *)((char *)(c+1) + sz);
*tail = DOGTAG_TAIL;
memset(c+1, 0xCC, sz);
return c+1;
}
void
my_free(void *p)
{
if (p==NULL)
return;
struct cookie * c = p;
--c;
assert(c->tag != DOGTAG_FREE);
assert(c->tag == DOGTAG_VALID);
int *tail = (int *)((char *)p + c->sz);
assert(*tail == DOGTAG_TAIL);
c->tag = DOGTAG_FREE;
memset(p, 0xCC , c->sz);
free(c);
}
int main() {
int* PtrInt = (int*)my_malloc(10);
*PtrInt = 10;
*(PtrInt+1) = 20;
my_free(PtrInt);
return0;
}
//Starting program: /Users/zhilihu/code/memoryManage/customMallocFree
//
//Breakpoint 1, main () at customMallocFree.c:50
//50 int* PtrInt = (int*)my_malloc(10);
//(gdb) n
//
//Breakpoint 2, my_malloc (sz=10) at customMallocFree.c:21
//21 + sz + sizeof(int));
//(gdb) n
//22 assert(c != NULL);
//(gdb) n
//23 c->sz = sz;
//(gdb) p c
//$3 = (struct cookie *) 0x100300080
//(gdb) p c+1
//$4 = (struct cookie *) 0x100300090
//(gdb) p (char*)(c+1)
//$5 = 0x100300090 ""
//(gdb) p sz
//$6 = 10
//(gdb) p (c+2)
//$7 = (struct cookie *) 0x1003000a0
//(gdb) p sizeof(struct cookie)
//$8 = 16
//