我正在为一个项目创建malloc,分配空间是理解它如何工作的困难方法,但我遇到了空指针问题。
(给定)块结构:链表
typedef struct block_hd{
/* The blocks are maintained as a linked list */
/* The blocks are ordered in the increasing order of addresses */
struct block_hd* next;
int size_status;
}block_header;
block_header* list_head = NULL;
当我添加内存块时,我的临时节点遇到了一个错误。基本上,它并不是取消引用temp_node来获取下一个temp_node并将其设置到正确的位置。我的打印报表:
not empty: 4088
there is space to add
create temp
f7758040
f7754000
00000000
Segmentation fault (core dumped)
它永远不会到达temp_node的下一个。就像它没有正确地创建临时。Temp指向块的标头。我会给它一个位置。问题出在哪里?
我的Mem_Alloc函数*假设正确启动的链表:
void* Mem_Alloc(int size)
{
if (size < 1) return NULL;
size = 1 + ((size - 1)/4);
size = size * 4;
if (list_head != NULL){
block_header* head_node = list_head;
while (head_node != NULL){
//get curr header size
int node_size = head_node->size_status;
printf("not empty: %dn", node_size);
//there is space to add
if (node_size%2 == 0 && (size+sizeof(block_header)) < node_size){
printf("there is space to addn");
//twocases
if ((node_size - size - sizeof(block_header)) > 0){
printf("create tempn");
block_header* temp_node = NULL;
temp_node = head_node + sizeof(block_header) + size;
printf("%08xn", (unsigned int) temp_node);
printf("%08xn", (unsigned int) head_node);
printf("%08xn", (unsigned int) head_node->next);
printf("%08xn", (unsigned int) temp_node->next);
printf("set temp next to head nextn");
temp_node->next = head_node->next;
printf("set temp size to remainingn");
temp_node->size_status = (head_node->size_status - sizeof(block_header) - size);
printf("set head size to used statusn");
head_node->size_status = size + 1;
printf("set head next to tempn");
head_node->next = temp_node;
}
else{
//if at end, and not enough space for another header
//keep current size_status - do not reduce current
printf("Not enough space, set head size to usedn");
if (head_node->next != NULL) head_node->size_status = size + 1;
}
//return location of (head_node_location+sizeof(block_header))
return head_node + sizeof(block_header);
}//end if
else{
//headersize%2 equaled 1, so it's used - move on.
printf("STEPPING THROUGH LINKED LISTn");
head_node = head_node->next;
}
}//end while
}//end if
return NULL;
temp_node
在此设置:
temp_node = head_node + sizeof(block_header) + size;
递增指针不是按字节计算的,地址是根据指针指向的类型计算的。因此,如果p
指向struct block_struct
数组的元素0,那么p+1
将指向索引1处的struct block_struct
,p+2
将指向索引2处的。
temp_node
的初始化似乎假定head_node
将增加若干字节。
您可以更改计算以处理struct block_struct
,也可以在执行指针运算之前将指针投射到char*
(char
是一个字节)。
您会被指针算术与类型的交互方式所绊倒。
temp_node = head_node + sizeof(block_header) + size;
我假设在这一行中,您正试图将指针size + sizeof(block_header)
字节提前。但由于指针指向的是block_header,因此它正在按字节计数乘以sizeof(block_head)。你可以做一些类似的事情:
/* Advance the pointer then cast */
char *raw_tmp_node = head_node + sizeof(block_header) + size;
block_header *tmp_node = (block_header*)raw_tmp_node;
顺便说一句,你应该读一读记忆对齐的重要性。malloc
保证它返回的内存对于任何类型都是适当对齐的。通常,这是通过强制与并集对齐来完成的,如K&R.
union align_storage {
most_strictly_aligned_type x; /* Usually a long; sometimes long long */
char storage[BLOCK_SIZE];
};