c - 链表指针打印内存泄漏

标签 c pointers struct linked-list

错误是它打印出内存而不是每个节点的值。我尝试了指针和不同打印样式的所有组合,但它们都显示为内存泄漏。

这是我的代码:

#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/

相关文章:

c - 在linux中的c程序中输入向上箭头键

c - 如果我们从 SAD 算法计算视差值,我们如何使用该值来制作视差图?方法是什么?

c - 无法在快速排序中正确传递数组

c - 作为指针传递时结构不保留数据

c++ - 在 C++ 中使用 memset 初始化具有不同值的结构数组元素

c++ - 结构体后的尖括号

c - 如何将 char[ ] 转换为 char * ?

C编程: Pointer arithmetics instead of index operations

c++ - 在 Visual Studio 2015 和 C++ 语言中没有初始化的指针

c - 释放指向指针的指针