c - 这两个地址怎么会不同呢?

标签 c pointers memory

我有一个结构

typedef struct    s_block
{
  size_t          size;
  struct s_block  *next;
  struct s_block  *back;
  int             free;
  void            *data;
}                 t_block;

我这样初始化它:

int       createHeader()
{
    void  *data;
    data = sbrk(BLOCK_SIZE + (sizeof(t_block) * 2));
    header = data;
    header->next = header;
    header->back = header;
    header->size = 0;
    createNewBlock(data + sizeof(t_block), BLOCK_SIZE + sizeof(t_block), 0);
    return 0;
}

void  *createNewBlock(void *beginAddress, size_t size, int free)
{
  printf("%d\n", size);
  t_block *newBlock;
  printf("first %p\n", beginAddress);
  printf("addr : %p\n", beginAddress + size);
  newBlock = beginAddress;
  newBlock->back = header->back;
  newBlock->next = header;
  newBlock->size = size;
  newBlock->free = free;
  newBlock->data = beginAddress + sizeof(t_block);
  header->back->next = newBlock;
  header->back = newBlock;
  header->size++;
  show_alloc_mem();
  return newBlock->data;
}

当我在 createNewBlock 中显示 beginAddress 时,给出的地址是好的,当我显示 beginAddress + size 的地址时,它给出给我正确的地址:

140
first 0x18f9028
addr : 0x18f90b4

但是当我进入我的函数时 show_alloc_mem()

void show_alloc_mem()
{
  t_block *tmp;

  tmp = header->next;
  printf("break : %p\n", header);
  while (tmp != header)
  {
    if (tmp->free == 1)
      printf("%p - %p : %d bytes\n", tmp, tmp + tmp->size, (int)tmp->size);
    else
      printf("free: %p - %p : %d bytes\n", tmp, tmp + tmp->size, (int)tmp->size);
    tmp = tmp->next;
  }
}

奇怪的行为发生了。 header 地址和 tmp 地址是正确的。但是 tmp + size 的地址不是。

break : 0x18f9000
free: 0x18f9028 - 0x18fa608 : 140 bytes

你知道为什么吗?

最佳答案

您正在执行指针运算,期望它的行为类似于整数运算。

表达式 tmp + tmp->size 的计算结果为 (int)tmp + sizeof(t_block)*( (int)tmp->size ) 因为你是将整数 (tmp->size) 添加到指向结构的指针(tmp 的类型为 t_block*)。

关于c - 这两个地址怎么会不同呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35160267/

相关文章:

c - 为什么我没有得到 “m” 的余数?

c - 在 linux 下,c 函数有疯狂的行为

c - C 预处理器插入的空格

c++ - 在 C++11 中使用什么更好,零或 NULL?

memory - 32位进程如何使用近4GB内存?

c - 使用 C 参数运行 shell 脚本的安全方法,工作示例

C++ 指向函数的指针作为参数

c - 关于 c 指针和 * & 运算符的问题

c - 为什么 malloc 使用零大小?

c++ - 如何确定 C++ 中标准库字符串或其他非基本数据类型的内存大小?