【问题标题】:Array of strings linked list - Segmentation fault字符串链表数组 - 分段错误
【发布时间】:2017-01-31 03:00:01
【问题描述】:

我有一个接受字符串数组的函数。它通过特定字符的存在来分隔所有这些字符串,在本例中为“|”。请参阅我之前的问题以获得更好的想法Split an array of strings based on character

所以,我有一个如下所示的字符串数组:

char ** args = {"ls", "-l", "|", "cd", "."}

我的 parseCmnds 函数应该遍历数组中的每个字符串并创建一个新的字符串数组,其中包含“|”之前的所有字符串特点。然后它创建一个链表,其中每个节点指向我创建的每个字符串数组,本质上将原始字符串数组分离为相互链接的单独字符串数组。

所以,我的解析循环应该创建类似这样的内容:

在第一次迭代中: char ** 命令 = {"ls", "-l", NULL}

第二次迭代 char ** command = {"cd", ".", NULL}

每次迭代后,我的函数都会创建一个新的链表节点并填充它。我根据我在上一个问题中得到的一些答案构建了代码(感谢一百万)。但是由于某种原因,我遇到了一个我无法弄清楚的分段错误。有人可以检查我的代码并让我知道我做错了什么吗?

typedef struct node {
    char ** cmnd; 
    struct node * next;
} node_cmnds;

node_cmnds * parseCmnds(char **args) {
    int i; 
    int j=0; 
int numArgs = 0;
node_cmnds * head = NULL; //head of the linked list
head = malloc(sizeof(node_cmnds));
if (head == NULL) { //allocation failed
    return NULL;
}
else {
    head->next = NULL; 
}

node_cmnds * currNode = head; //point current node to head

for(i = 0; args[i] != NULL; i++) { //loop that traverses through arguments
    char ** command = (char**)malloc(maxArgs * sizeof(char*)); //allocate an array of strings for the command

    if(command == NULL) { //allocation failed
        return NULL;
    }

    while(strcmp(args[i],"|") != 0) { //loop through arguments until a | is found
        command[i] = (char*)malloc(sizeof(args[i])); //allocate a string to copy argument
        if(command[i] == NULL) { //allocation failed
            return NULL;
        }
        else {
            strcpy(command[i],args[i]); //add argument to our array of strings
            i++;
            numArgs++;
        }
    }

    command[i] = NULL; //once we find | we set the array element to NULL to specify the end

    while(command[j] != NULL) {
        strcpy(currNode->cmnd[j], command[j]);
        j++;

    }


    currNode->next = malloc(sizeof(node_cmnds));
    if(currNode->next == NULL) {
        return NULL;
    }
    currNode = currNode->next; //
    numArgs = 0;

} 

return head;

}

【问题讨论】:

  • 设置错误在代码的什么地方出现?
  • command[i] = (char *)malloc(sizeof(args[i])); --> command[i] = malloc(strlen(args[i]) + 1); -- sizeof(args[i])char * 的大小,而不是它指向的字符串的长度。
  • 另外... while(strcmp(args[i],"|") != 0) { 应更改为检查args 的结尾以及"|"。您要么需要知道args 中的字符串数,要么在args 的末尾加上NULL 来标记结束。

标签: c


【解决方案1】:

您永远不会为node_cmdscmnd 成员分配任何内存。所以strcpy(currNode->cmnd[j], command[j]); 正在写信给……某处。可能会记住你并不拥有。当你添加那些mallocs 时,你的索引(使用j)在第二次通过外部for 循环时将非常不正确。

此外,您正在像筛子一样泄漏内存。尝试在那里扔一些frees。

【讨论】:

    【解决方案2】:
    while(command[j] != NULL) {
        strcpy(currNode->cmnd[j], command[j]);
        j++;
    
    }
    

    在此语句中,您尚未为 cmnd 指针(字符串)分配内存。我相信这可能会导致您的部分问题。您已经为 struct 分配了内存,但您还需要为 struct 中的每个指针分配内存。

    【讨论】:

    • 这绝对是我的代码的问题。我确保分配内存,现在似乎一切正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-19
    • 1970-01-01
    • 2019-01-28
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多