gpt4 book ai didi

c - 内存泄漏检测导致错误

转载 作者:行者123 更新时间:2023-11-30 18:31:37 26 4
gpt4 key购买 nike

基本上我有内存泄漏。所以我想修复它们!在一些函数中添加了free()。运行 valgrind 并收到成功消息“所有泄漏内存已修复”或类似的信息!之后我遇到了一堆错误:(我想我已经把 free() 放对了。很容易混淆,因为有节点作为指针,节点作为结构(查看 file.h)。任何帮助表示赞赏.谢谢。抱歉,如果这个问题很简单。我是初学者......

file.h 中的代码

struct node {
int value;
struct node * next;
};
typedef struct node List;

int is_empty(List *);
List *add_node(List *, int);
List *remove_node(List *, int);
List *create_node(int);
char *tostring(List *);

file.c 中的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"

#define STRSIZE 128 /*assume string representation fits*/

/* Return true if the list h is empty
* and false otherwise.
*/
int is_empty(List *h) {
return h == NULL;
}

/* Create a list node with value v and return a pointer to it
*/
List *create_node(int v) {
List *node = malloc(sizeof(List));
free(node);
node->value = v;
node->next = NULL;
return node;
}

/* Insert a new node with the value v at the
* front of the list. Return the new head of
* the list.
*/
List *add_node(List *h, int v) {
List *node = create_node(v);
node->next = h;
return node;
}

/* Remove the first node in the list h that
* has the value v. Return the head of the
* list.
*/
List *remove_node(List *h, int v) {
List *curr = h;

/* Handle the cases when list is empty or the value
* is found at the front of the list */
if (h == NULL) {
return h;
} else if (h->value == v) {
h = h->next;
return h;
}

/* Look for the value in the list (keeping the pointer to
* the previous element so that we can remove the right
* element) */
while (curr->next != NULL && curr->next->value != v) {
curr = curr->next;
}

if (curr->next == NULL) { /* v is not in list so do nothing */
return h;
} else { /* curr->next->value == v */
curr->next = curr->next->next;
return h;
}
}

/* Return a string representation of the list pointed to by h.
*/
char *tostring(List *h) {
char *str= malloc(STRSIZE);
char num[4]; /* assume integer has max. four digits*/
free(str);
str[0] = '\0';
while (h != NULL) {
sprintf(num, "%d", h->value);
strncat(str, num, STRSIZE - strlen(str) - 1);
h = h->next;
}
return str;
}

最佳答案

也许你想要

temp = curr->next;
curr->next = curr->next->next;
free (temp);

在代码的当前状态下,remove_node 存在泄漏(如果删除所有节点,实际上会泄漏整个列表)。

此外,为了阻止 tostring 函数中的内存泄漏,该函数的调用者有责任释放 tostring 返回的字符串。

关于c - 内存泄漏检测导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21618881/

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