我正在用 C 语言开发自定义 malloc 和 free 实现。我的代码工作正常,但并不完美。在测试 my_malloc 和 my_free 的文件中,我调用 my_malloc 3 次。它适用于前 2 个调用,但不适用于第三个调用。一切都一模一样,所以我真的不知道为什么它不能再工作了。我知道堆中有足够的内存,所以不是这样的。它甚至可以返回指针变量的地址,但测试文件不会写入它。
这是测试 my_malloc 和 my_free 的代码,它与 c 中断:
static int *base;
static int *heap_end;
int total_mem_used = 0;
int first_call = 1;
int i;
int *a, *b, *c;
if ((a=(int *)my_malloc(10))==NULL)
return MALLOC_FAIL;
for (i=0;i<10;i++)
a[i] = i;
for (i=0;i<10;i++)
printf("%d\n", a[i]);
if ((b=(int *)my_malloc(18))==NULL)
return MALLOC_FAIL;
for (i=0;i<18;i++)
b[i] = i*i;
for (i = 0; i < 18; i++)
printf("%d ", b[i]);
printf("\n");
if ((c=(int *)my_malloc(5))==NULL)
return MALLOC_FAIL;
for (i=0;i<5;i++)
c[i] = i*7;
这也是 my_malloc,如果有帮助的话:
void *p;
int *t;
int data_size, block;
if (size==0)
return NULL;
if (first_call) {
if ((base=(int *)malloc(HEAP_SIZE))==NULL)
return NULL;
init_heap(norm_size(size)+8);
heap_end = &base[HEAP_SIZE];
first_call = 0;
total_mem_used += (norm_size(size)+2);
t = base;
return (void *) (t+2);
}
data_size = norm_size(size);
block = data_size + 2;
p = find_first_free(block);
if (p==0) {
errno = ENOMEM;
return NULL;
}
total_mem_used += block;
fill_header((int *) p, block);
t = (int *) p + 2;
return (void *) t;
void my_free(void *p) {
int *t;
t = (int *) p - 2;
*t = *t & -2;
coalesce(t);
}
void *find_first_free(int n) {
int *p;
p = base;
while (p<heap_end && ((*p & 1) || (*p <= n)))
p = p + (*p & -2);
return (void *)p;
}
int norm_size(int w) {
if (w % 8 == 0)
return w;
else
return w + (8 - w % 8);
}
void init_heap(int n) {
base[0] = n+1; // n+1 since we're allocating it
base[1] = (int) &base[n];
base[n-1] = n+1;
base[n] = HEAP_SIZE - n;
base[HEAP_SIZE-1] = HEAP_SIZE - n;
}
void fill_header(int *p, int w) {
p[0] = w+1;
p[1] = (int) &p[w];
p[w-1] = w+1;
p[w] = HEAP_SIZE - total_mem_used;
p[w+HEAP_SIZE-total_mem_used-1] = HEAP_SIZE - total_mem_used;
}
知道这个程序到底出了什么问题吗?感谢您的帮助。
最佳答案
避免魔数(Magic Number)
<小时/>block = data_size + 2;
为什么是 2?为什么不是 16 或 256?当然,添加是为了节省尺寸。在这种情况下,请添加 int
的大小。
block = data_size + sizeof(int);
<小时/>
t = (int *) p + 2;
为什么是 2 而不是其他数字?同样,这样做是为了考虑在 p
处开始保存的大小。但这不是像以前那样的整数加法。这就是“指针加法”。使用 + 2
时,p
会增加 2 * sizeof(int)
。可能的代码应该是
t = p + 1;
这是“无魔数(Magic Number)”规则的一个异常(exception):-1,0,+1 都可以
<小时/>要回答更多问题,请发布完整的功能。
<小时/>次要:不需要 Actor
// if ((base=(int *)malloc(HEAP_SIZE))==NULL)
if ((base = malloc(HEAP_SIZE)) == NULL)
次要:考虑无符号类型size_t
。这是由 strlen()
、sizeof()
// int data_size
size_t data_size
// if ((a=(int *)my_malloc(10))==NULL)
a = my_malloc(10);
if (a == NULL)
为什么init_heap(norm_size(size)+8);
中是8?使用常量/定义
#define MY_MALLOC_GUARD (8)
init_heap(norm_size(size) + MY_MALLOC_GUARD);
关于c - 自定义 malloc 实现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27389811/