每个节点都是8个字节,我在程序中分配3个(8 * 3 = 24),所以我假设内存丢失了。
这是valgrind错误
24 (8 direct, 16 indirect) bytes in 1 blocks are definitely lost in loss record 3 of 3
==2381== at 0x402BE68: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2381== by 0x8048598: mh_alloc (in /media/sf_Z_DRIVE/comp2401a4/a4)
==2381== by 0x8048857: main (in /media/sf_Z_DRIVE/comp2401a4/a4)
这是BlockType,它是节点携带的数据。
typedef struct {
int rsv;
void *addr;
int size;
char tag[MAX_STR];
} BlockType;
这是valgrind说丢失数据的地方。
void *mh_alloc(HeapType *heap, int n, char *label){ //this is the allocation function
BlockType *blk;
blk = (BlockType *)malloc(sizeof(BlockType));
blk->rsv = C_TRUE; //set block to reserved
blk->addr = blk; //set the address to keep track of where the block is stored in memory
blk->size = n; // set the size of the block
strcpy(blk->tag, label); //add the name of the block
Node *temp2 = malloc(sizeof(struct Node));
temp2->block = blk;
temp2->next = NULL;
if (heap->head == NULL) {
heap->head = temp2;
}
else{
struct Node *temp = heap->head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = temp2;
}
return blk; //we return blk because we assign pointers to such blocks in the main function.
}
这个函数在最后调用以释放所有块和节点 - >
void mh_collect(HeapType *heap){ //function to unreserve all elements in the array, and free each address
struct Node *temp = heap->head;
struct Node *prev = NULL;
if (temp->next == NULL){
printf("Only the head left");
temp->block->rsv = C_FALSE;
return;
}
while(temp != NULL){
temp->block->rsv = C_FALSE;
free(temp->block->addr);
temp = temp->next;
}
}
答案 0 :(得分:0)
编辑:(原始问题已修改)
此代码看起来不对:
while(temp != NULL){
temp->block->rsv = C_FALSE;
free(temp->block->addr);
temp = temp->next;
}
在循环中,您不会释放节点temp
本身。请注意,这不会“泄漏”任何内存,但确实会让内存闲置。你可能想要考虑这样的事情:
while(temp != NULL){
Node *next = temp->next;
temp->block->rsv = C_FALSE; // Seems useless because you are freeing it.
free(temp->block); // Note: temp->block->addr == temp->block
free(temp);
temp = next;
}
此外,如果您分配给block->addr
以外的其他内容,那么这可能是您泄密的原因。我不确定block->addr
的用途是什么,但我建议删除它,除非它用于其他目的。