![](/img/trans.png)
[英]How to map two virtual adresses on the same physical memory on linux?
[英]How these two adresses can be different ?
我有一个结构
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;
}
}
发生奇怪的行为。 标头地址和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*
)。
您使用两种不同的指针算法:
void *
t_block *
您的编译器允许您对void *
进行算术运算,但标准未包括在内。 一些编译器(您的)对void *
使用自然算术,因此在第一个表达式中它计算BaseAdressValue+size
而在第二个表达式中则计算BaseAdressValue+size
BaseAddressValue+40*size
(40是结构的大小,五个8字节指针,您位于64位指针平台)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.