我的問題是,根據我的教授的說法,在程式 A 中,get_Name() 會導致記憶體泄漏,但在程式 B 中不會導致任何問題。我不明白為什么會這樣!
據我所知,get_Name() 應該發生記憶體泄漏,因為使用了 malloc()。我不明白為什么是案例A?任何答案將不勝感激。
方案一:
struct actor {
char name[32];
struct actor *next;
} *head = NULL;
char *get_name()
{ char *q;
q = (char *) malloc(32);
printf("Please enter a name: ");
scanf("%s", q); return q;
};
int insertion()
{struct actor *c; char *n;
c = malloc(sizeof(struct actor));
if (c == 0) {
printf("out of memory\n"); return -1;}
n = get_name();
strcpy(c->name, n);
c->next = head;
head = c;
return 1
};
方案 B:
struct actor {
char *name;
struct actor *next;
} *head = NULL;
char *get_name()
{ char *q;
q = (char *) malloc(32);
printf("Please enter a name: ");
scanf("%s", q); return q;
};
int insertion()
{struct actor *c; char *n;
c = malloc(sizeof(struct actor));
if (c == 0) {
printf("out of memory\n"); return -1;}
c->name = get_name();
c->next = head;
head = c;
return 1
};
uj5u.com熱心網友回復:
insertion()來自樣本 A 字串的方法將結果復制get_name()到一個新字串中,而樣本 B 中的插入將獲得的指標復制到一個從頭開始的串列中。在程式后面的某個地方,必須有一個地方通過呼叫free(). 這在示例 A 中是不可能的,因為指向用 malloc() 分配的字串的指標在離開后丟失了insertion()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/519685.html
標籤:C指针记忆内存泄漏
下一篇:在C中的編譯時將空陣列分配給指標
