【发布时间】:2016-01-23 13:45:20
【问题描述】:
我想知道我应该释放分配给链表的内存的抑制函数出了什么问题。
这是我的代码:
typedef struct cell {
int number;
struct cell *next;}cell;
typedef struct {
int sign; //1 or 0
int nbrCell ;
cell *numbers;} num ;
初始化函数:
num *initialisation(){
num *num = malloc(sizeof(*num));
cell *cell =malloc(sizeof(*cell));
num->numbers = cell;
cell->next=NULL;
num->sign= 0 ;
num->nbrCell =0;
return num ;}
删除过程
void suppression(num* num){
cell* Delete;
cell* newC = num->numbers;
while (newC)
{
Delete = newC;
newC = newC->next;
free(Delete);
}
}
现在在我的主目录中
int main(){
num* number;
number=initialisation();
suppression(number);
return 0;
}
当我尝试使用 valgrind 时,它会说:
==21281== HEAP SUMMARY:
==21281== in use at exit: 16 bytes in 1 blocks
==21281== total heap usage: 2 allocs, 1 frees, 32 bytes allocated
==21281==
==21281== 16 bytes in 1 blocks are definitely lost in loss record 1 of 1
==21281== at 0x4C2AB80: malloc (in /usr/lib/valgrind /vgpreload_memcheck-amd64-linux.so)
==21281== by 0x4005CE: initialisation (test.c:26)
==21281== by 0x4006D5: main (test.c:85)
==21281==
==21281== LEAK SUMMARY:
==21281== definitely lost: 16 bytes in 1 blocks
==21281== indirectly lost: 0 bytes in 0 blocks
==21281== possibly lost: 0 bytes in 0 blocks
==21281== still reachable: 0 bytes in 0 blocks
==21281== suppressed: 0 bytes in 0 blocks
==21281==
==21281== For counts of detected and suppressed errors, rerun with: -v
==21281== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
即使我尝试插入一些数字,我总是会得到额外的 1 个分配,比如 5 个分配,4 个释放..
在我的项目中我使用数字结构来保存数字
像 1->2->3->4->5->6->NULL 2 是 num->numbers->next 等。
每次我添加一个数字时,它都会被放入一个单元格中,然后我将该单元格添加到数字结构中。 现在我想知道如何释放 num,当然也释放它拥有的所有单元格..
插入函数
void insertion(num *number, int element ){
cell *cellule = malloc(sizeof(*cellule));
if (number == NULL || cellule == NULL)
{
exit(-1);
}
cellule->number = element;
cellule->next = number->numbers;
number->numbers = cellule;
number->nbrCell++ ;
}
【问题讨论】:
-
您能告诉我们您是如何将元素添加到您的列表中的吗?
-
好的,但是在这个例子中我没有添加任何元素,它只是列表的初始化并试图删除它,我将添加我用来添加元素的代码
-
您在问题中的代码对我有用,没有分段错误。
-
是的,我又试了一次,现在它可以工作了,但是当我使用 assert(number==NULL);它给了我一个错误,这意味着该号码仍在分配..
-
所以一个 free 没有被执行,你应该使用 gcc 或几个 printf() 来检查它。
标签: c linked-list segmentation-fault malloc free