c中的小型链表程序,随机输出printf

问题描述 投票:0回答:1

[我正在编写一些学校课程,我必须使用'void const * content'作为参数。我在打印新节点的内容时遇到问题。没有'const'的代码可以工作并显示正确的所有内容。有人可以指出我在做什么错吗?

终端输出: � 6


#include <stdio.h>
#include <stdlib.h>

    typedef struct s_list
    {
        void        *content;
        size_t      content_size;
        struct      s_list *next;
    }               t_list;

t_list  *lstnew(void const *content, size_t content_size)
{
    struct s_list *new = (struct s_list*)malloc(sizeof(struct s_list*));
    if(new == NULL){
        printf("No allocation!");
        exit(1);
    }

    new->content = &content;
    new->content_size = content_size;
    new->next = NULL;


    return(new);
}

int     main(void)
{

    printf("%s\n", lstnew("Hello", 6)->content);
    printf("%zu\n", lstnew("Hello", 6)->content_size);

    return(0);
}

c linked-list printf undefined-behavior singly-linked-list
1个回答
0
投票

您要在此处使用局部变量的地址:

new->content = &content;

相反,只需取值:

new->content = content;

此外,您在这里没有分配足够的内存;您只为指针分配了足够的空间,而不是结构的大小:

struct s_list *new = (struct s_list*)malloc(sizeof(struct s_list*));

malloc上的强制转换也是不必要的。我会这样写:

struct s_list *new = malloc(sizeof(*new));

而不是使用typedef,您应该只在各处使用struct s_list,因为该结构并非旨在不透明。

© www.soinside.com 2019 - 2024. All rights reserved.