私はちょうどCとリンクリストについて学んでいます。私はいくつかの大きな問題があります。cのリンクリストの最後の項目を削除する際の問題
私は、次のコードしている:私はJavaScriptからArray.prototype.pop
に似て動作するようになっているポップを実行すると
#include <stdio.h>
#include <stdlib.h>
struct people {
int age;
char *name;
struct people * next;
};
typedef struct people people;
void count(people array) {
people *current=malloc(sizeof(people));
current = &array;
int count = 0;
while(current){
count++;
printf("name %s\n",current->name);
printf("age %d\n",current->age);
current=current->next;
}
printf("%d\n", count);
free(current);
}
void push(people *array){
people * new=malloc(sizeof(people));
people *last=malloc(sizeof(people));
new->age=300;
new->name="baz";
new->next=NULL;
last=array;
while(last->next){
last=last->next;
}
last->next=new;
// free(new);
}
void pop(people *array){
people * last=malloc(sizeof(people));
last=array;
while(last->next){
//get the last element in the list
last=last->next;
}
// free the last element
free(last);
}
int main(int argc, char** argv) {
people person = {
.name = "foo",
.age = 25
};
person.next = malloc(sizeof (people));
person.next->age = 26;
person.next->name = "bar";
person.next->next = NULL;
//push into the list
push(&person);
//count after pushing
count(person);
//remove last
pop(&person);
//at this count i get just the age 0 but the name was not removed and still counts 3
count(person);
return 0;
}
を。
最後のnext
の名前は "baz"で、年齢は300です。この最後の構造体を削除する代わりにこのコードを実行した後、年齢は0になります。
無料のポインタは割り当てられていませんmallocで。
最後のone-before-lastは無効なメモリを指しています。 free()は指定されたメモリチャンクをメモリアロケータに返すだけで、ポインタは有効なメモリに設定されません。 – GeorgeAl
@GeorgeAlコメントに加えて、たくさんのメモリがリークします。現在のものと最後のものが自分の記憶を得たら、ポインタを他のアドレスに割り当てることによってそれをドロップするだけです。 – Andreas
@GeorgeAlどのように私は自由に動作しない場合、割り当てられたメモリピースを解放するのですか? – nikoss