【问题标题】:Subtracting one address from another address in C从C中的另一个地址减去一个地址
【发布时间】: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


【解决方案1】:

指针算术不支持操作(指针+指针)。唯一允许的操作是 (Pointer + Integer) 所以结果是一个指针。

要获得偏移量,您需要将两个指针都转换为整数类型。结果值是整数而不是指针。

例子:

int offset = (int)ptr - (int)heap;

printf("ptr : %p\n", ptr);
printf("heap : %p\n", heap);
printf("offset: %d\n", offset);

而且heap 的值太大而无法存储在单个字节中,这就是为什么将其转换为char 类型会返回值为零。

【讨论】:

    【解决方案2】:

    指针算法只对特定类型有意义。在这个例子中,int类型的大小为4,但指针减法只有1。

    #include <stdio.h>
    
    int array[2];
    int *a, *b;
    
    int main(void){
        a = &array [0];
        b = &array [1];
        printf ("Int size = %d\n", sizeof(int));
        printf ("Pointer difference = %d\n", b-a);
        return 0;
    }
    

    程序输出:

    Int size = 4
    Pointer difference = 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 2017-12-10
      • 1970-01-01
      相关资源
      最近更新 更多