首页 > 解决方案 > 如何在没有段错误的情况下正确地将 char* 添加到链表

问题描述

我正在尝试将值(文件路径的字符数组)添加到链表。我不断从我的 _add 函数中得到一个 Seg 错误,我不知道如何修复它。我尝试了许多不同的方法来编写函数,但我一无所获。答案似乎很简单,我就是不明白。这是我的 _add 函数代码:

    typedef struct cplist {
        char *path; 
        int cpid;
        time_t  tv_sec;   
        suseconds_t tv_usec;
        struct cplist *next;
    } cplist;

cplist *cpl_add(cplist *head, char *path){
    cplist *current = head;
    while(current->next != NULL){
        current = current->next;
    }

    current->next = (cplist*) malloc(sizeof(cplist));
    current->next->path = path;
    current->next->next = NULL;
}

这是我在主程序中的代码。我正在读取一个可选的“-v”标志,然后是一个整数,然后是必须添加到链表的路径:

int main(int argc, char* argv[]){
    int i, j;
    char *p;
    char *key;
    cplist *head = NULL;
    for(i = 0; i < argc; i++){
        if(strcmp(argv[1], "-v") == 0){
            key = argv[2];
            for(j = 3; j < argc; j++){
                p = argv[j];
                cpl_add(head, p);
            }
        } else {
            key = argv[1];
            for(j = 2; j < argc; j++){
                p = argv[j];
                cpl_add(head, p);
            }
        }
    }

标签: clinked-listsegmentation-fault

解决方案


该函数通常是不正确的,因为当最初传递的指向 head 的指针等于 NULL 时,它不处理列表。

你应该复制传递的字符串。

此外,该函数的返回类型不同于void但不返回任何内容。

除此之外,它在此声明中有一个错误

current->next = (cplist*) malloc(sizeof(head));

您没有为节点分配内存。您正在为指针分配内存。这是不一样的。

该函数可以如下所示。

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

//...

int cpl_add( cplist **head, const char *path )
{
    cplist *current = malloc( sizeof( cplist ) );

    int success =  current != NULL;

    success = success && ( current->path = malloc( strlen( path ) + 1 ) );

    if ( !success )
    {
        free( current );
    }
    else
    {
        strcpy( current->path, path );
        current->next = NULL;

        while ( *head != NULL ) head = &( *head )->next;

        *head = current;
    }

    return success;
}

并调用该函数,例如

cpl_add( &head, argv[j] );

推荐阅读