gpt4 book ai didi

c - Valgrind 错误可能与 c 中的 malloc 有关

转载 作者:太空宇宙 更新时间:2023-11-04 07:02:17 25 4
gpt4 key购买 nike

我的代码有问题。我收到 valgrind 错误,这与 malloc 有关。我很困惑,因为我对代码的其他部分没有任何问题,这些部分与我遇到问题的部分完全相同。我得到的错误是:

==15151==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)                                                          
==15151== by 0x4006E2: main (additup.c:28)




struct bigInt {
int digit;
struct bigInt *next;
struct bigInt *prev;
};

struct bigInt* curInt;
struct bigInt* intHead;
struct bigInt* intTail;
struct bigInt* curSum;
struct bigInt* sumHead;
struct bigInt* sumTail;

int main(){
int addSum(int i );
curInt = malloc(sizeof(struct bigInt));
intHead = malloc(sizeof(struct bigInt));
intTail = malloc(sizeof(struct bigInt));
curSum = malloc(sizeof(struct bigInt)); // Problem: line 28
sumHead = malloc(sizeof(struct bigInt)); //Problem: line 29
sumTail = malloc(sizeof(struct bigInt)); //Problem: line 30
addSum(11); //add head to sum linked list
addSum(99);//add tail to sum linked list
addSum(0);

int addSum(int i){ //adds sum structure to front of linked list
struct bigInt* x = malloc(sizeof(struct bigInt));
if(i==11){
x->digit=i;
sumHead=x;
curSum=x;
} else {
x->next=sumHead->next;
sumHead->next=x;
x->prev=sumHead;
curSum=x;
x->digit=i;
if(i==99) sumTail=x;
}
return 0;
}

如有任何帮助,我们将不胜感激。谢谢`

最佳答案

 addSum(99);//add tail to sum linked list
//...
if(i==99) sumTail=x;

那是内存泄漏。 sumTail 指向的先前 malloc block 不再可访问。 ...另外两个方 block 也以同样的方式丢失。

关于c - Valgrind 错误可能与 c 中的 malloc 有关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36554554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com