【发布时间】:2015-01-26 14:35:38
【问题描述】:
在一个家庭作业项目中,我必须从另一个指针中减去一个指针的地址。 这是我尝试编写的一段代码,用于从给定的元数据地址中减去 void* 类型的堆。哪里不对。
metadata_t* getBuddy(metadata_t* ptr)
{
metadata_t* offset = ptr - (char)heap;
int h = (char)heap;
#ifdef DEBUG
printf("ptr : %p\n", ptr);
printf("heap : %p\n", heap);
printf("offset: %p\n", offset);
printf("char : %d\n", h);
#endif
return NULL;
}
这是我得到的输出:
ptr : 0x7fe7b3802440
heap : 0x7fe7b3802200
offset: 0x7fe7b3802440
char : 0
这是我预期的输出:
ptr : 0x7fe7b3802440
heap : 0x7fe7b3802200
offset: 0x000000000240
char : 0x7fe7b3802200
问题:
1) 为什么 char 输出为零? (这不是我在做什么:将指针转换为单个字节,然后将其存储到 int 中)
2) 如果这不是您正确执行指针运算的方式,那么您将如何完成偏移量?
编辑:
1) 我认为堆被定义为 int*。这是返回其值的给定代码。
#define HEAP_SIZE 0x2000
void *my_sbrk(int increment) {
static char *fake_heap = NULL;
static int current_top_of_heap = 0;
void *ret_val;
if(fake_heap == NULL){
if((fake_heap = calloc(HEAP_SIZE, 1)) == NULL) {
return (void*)-1;
}
}
ret_val=current_top_of_heap+fake_heap;
if ((current_top_of_heap + increment > HEAP_SIZE)
|| (current_top_of_heap+increment < 0)) {
errno=ENOMEM;
return (void*)-1;
}
current_top_of_heap += increment;
return ret_val;
}
【问题讨论】:
-
这段代码没有意义。指针 - 指针不给出另一个指针。
heap是如何定义的?
标签: c memory dynamic malloc allocation