while(n >= 0);
node * point = malloc(sizeof(node));
point = create(number, n);
//show(point);
//free memory
while(point != NULL)
{
node *tmp = point->next;
free(point);
point = tmp;
}
}
node * create(int data[], int len)
{
node * list_head;
node * list;
for (int i = 0; i < len; i )
{
if(i == 0)
{
list_head = malloc(sizeof(node));
list = malloc(sizeof(node));
list_head->value = data[0];
list_head->next = list;
}
else
{
list->value = data[i];
list->next = malloc(sizeof(node));
list->next = NULL;
}
}
return list_head;
}
此代碼回傳一個錯誤,即:- free(): invalid pointer Aborted | 為什么我的代碼沒有釋放我分配的記憶體。是不是因為我在一些不同的函式中分配了它?
uj5u.com熱心網友回復:
您發布的代碼應更改為:
while(n >= 0) {
node * point = create(number, n);
和:
list->next = NULL;
應該改為
list = list->next;
uj5u.com熱心網友回復:
您完全誤解了 C 中的記憶體管理。指標指向事物。
- 有時它們是不確定的(你從未確定它們指向什么)。
- 有時它們指向動態事物(使用堆函式分配,例如
malloc) - 有時他們指向自動的東西 (
int i; int *p = &i;) - 有時他們故意指向任何內容(例如
NULL)
像這樣的行:
node * point = malloc(sizeof(node));
point = create(number, n);
是保證記憶體泄漏的秘訣。
node * point = malloc(sizeof(node));使用 分配記憶體malloc,將結果地址存盤在指標中point。point = create(number, n);呼叫一些函式create,將回傳的任何內容存盤在同一個指標中point,從而孤立剛剛在(1)中分配的記憶體。該記憶體現在沒有指標保存它之前的地址,因此記憶體泄漏。
看到問題了嗎?同樣的問題在代碼中進一步出現:
list->next = malloc(sizeof(node));
list->next = NULL;
C 不是 Java。并不是所有的東西都需要新的(或 malloc 的)僅僅因為涉及一個指標。例如:
int i = 42;
int *p1 = &i; // p1 now holds the address of the 'i' variable.
int *p2 = p1; // p1 and p2 both now hold the address of the 'i' variable.
p1 = NULL; // p1 no longer points to 'i'
p2 = p1; // p2 no longer points to 'i' now either.
一個除錯器,并通過你的代碼,以監視變數,它們的值單步執行,而且如果是三分球,他們指向(如果有的話)是一個令人難以置信的工具,我強烈建議你盡快擁抱一個。我不知道你是從哪個網站/文本中學習到這一點的,但我強烈建議你使用另一個參考資料,最好是在實際教學方面享有良好聲譽的參考資料(如果有必要,還包括更換教授)。
也就是說,通過正向鏈接創建鏈表是直接的。
#include <stdio.h>
#include <stdlib.h>
// our node
typedef struct node node;
struct node
{
int value;
node *next;
};
// create a simple linked list from an array
node *create_list(const int ar[], int len)
{
node *list = NULL, *cur = NULL;
for (int i=0; i<len; i)
{
node *p = malloc( sizeof *p );
if (p == NULL)
{
perror("Failed to allocate new list node");
break;
}
p->value = ar[i];
if (cur)
{
cur->next = p;
}
else
{
list = p;
}
cur = p;
}
if (cur)
{
cur->next = NULL;
}
return list;
}
void free_list(node *list)
{
while (list)
{
node *tmp = list;
list = list->next;
free(tmp);
}
}
void print_list(const node *list)
{
while (list)
{
printf("%d ", list->value);
list = list->next;
}
fputc('\n', stdout);
}
int main()
{
int ar[] = { 1,2,3,4,5,6,7,8,9,10 };
node *list = create_list(ar, sizeof ar / sizeof *ar);
print_list(list);
free_list(list);
return EXIT_SUCCESS;
}
輸出
1 2 3 4 5 6 7 8 9 10
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/400660.html
上一篇:比較數字和陣列
下一篇:從熊貓資料框中的索引獲取前后的行
