错误是它打印出内存而不是每个节点的值。我尝试了指针和不同打印样式的所有组合,但它们都显示为内存泄漏。
这是我的代码:
#include <stdio.h>//headers
#include <stdlib.h>
struct node{
int val;
struct node *next;
};//linked list
struct node *curr = NULL;//list pointers
struct node *prev = NULL;
struct node *head = NULL;
int main(){
int i;
struct node *curr = (struct node*) malloc(sizeof(struct node));
head=curr;//sets head node
for (i=1;i<=5;i++){
curr->val=i;//sets data
struct node *prev = (struct node*) malloc(sizeof(struct node));
curr->next=prev;
curr=prev;//links to previous node
printf("%d\n", *curr);//prints out data
}
return 0;
}
最佳答案
好吧,您的程序中没有调用 free
,所以是的,每次调用 malloc
从技术上讲都是泄漏。也就是说,我认为您在这里混淆了您的术语。
如果要打印出节点的值,使用cur->val
,而不是*cur
。 *cur
返回一个 struct node
,您告诉 printf
将其解释为 int
。
关于c - 链表指针打印内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27711189/