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

small linked list programme in c, random printf output

我正在写一个小学校程序,我必须使用 '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);
}

您正在获取局部变量的地址:

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));

与其使用 typedeft_list,不如在任何地方都使用 struct s_list,因为该结构并非旨在不透明。

在此声明中

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

不是为 struct s_list 类型的对象分配内存,而是为 struct s_list *.

类型的指针分配内存

你必须写任何一个

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

t_list *new = malloc( sizeof( t_list ) );

在此声明中

new->content = &content;

左侧操作数的类型为 void *,而右侧操作数的类型为 const void **。此外,您正在使用指向局部变量 content (函数参数是其局部变量)的指针,该指针在退出函数后将不存在。

你需要的是分配内存,在分配的内存中拷贝变量content的内容

这是一个演示程序,展示了如何定义函数。

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

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

t_list * lstnew( const void *content, size_t content_size )
{
    t_list *new = malloc( sizeof( t_list ) );

    if ( new != NULL )
    {
        new->content = malloc( content_size );

        if ( new->content == NULL )
        {
            free( new );
            new = NULL;
        }
        else
        {
            memcpy( new->content, content, content_size );
            new->content_size = content_size;
            new->next = NULL;
        }
    }

    return new;
}


int main(void) 
{
    t_list *head = lstnew( "Hello", 6 );
    head->next = lstnew("World!", 7 );

    printf( "%s %s\n", ( char * )head->content, ( char * )head->next->content );

    return 0;
}

程序输出为

Hello World!