基本上,我有內存泄漏。所以我想解決它們!在某些函數中添加了free()。運行valgrind並獲得成功消息所有泄漏記憶都是固定的或者不正確的!然後我有一堆錯誤:(我認爲我已經把免費()正確的。很容易感到困惑,因爲有節點作爲指針和節點作爲一個結構(看在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;
}
修復內存泄漏是剛剛得到充分的理解你的程序的最佳途徑。 – moeCake