【发布时间】:2016-09-10 12:09:59
【问题描述】:
我刚学c,关于链表我有一些大问题。
我有以下代码:
#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;
}
当我运行 pop 时,它的工作方式应该类似于 Javascript 中的 Array.prototype.pop。
最后一个next 的行为非常奇怪,其名称为“baz”,年龄为 300。在我运行此代码而不是删除最后一个结构后,它只显示年龄为 0。
似乎 free 并没有真正释放使用 malloc 分配的指针。
【问题讨论】:
-
虽然最后一个仍然指向无效内存。 free() 只是将给定的内存块返回给内存分配器,不会将指针设置为有效内存
-
除了@GeorgeAl 评论之外,您还泄漏了大量内存。当前和最后一次获得自己的内存,然后您只需通过将指针分配给其他地址来删除它。
-
@nikoss,你需要设置
one-before-last->next = NULL;。也可以尝试向自己解释为什么要尽可能地使用malloc()。例如,为什么pop()你malloc()在第一行? -
@nikoss,你需要一本好的 C 入门书
-
@nikoss 好的。我建议你不要通过编码和调试从头开始学习 c。指针和内存并没有那么复杂,但你可以对它的工作原理进行逆向工程。
标签: c arrays struct linked-list malloc