c - 字符串数组链表 - 段错误

标签 c

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

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

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

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

所以,我的解析循环应该创建这样的东西,例如:

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

第二次迭代 char ** 命令 = {"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;

}

最佳答案

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

此外,您正在像筛子一样泄漏内存。尝试将一些 free 放入其中。

关于c - 字符串数组链表 - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41948991/

相关文章:

c++ - C 中的副作用

C数组指针段错误

c - 在执行期间手动将 stdin 重定向到文件

c++ - COM 函数产生不会消失的线程

c - 我怎样才能使这种按位运算更快?

c++ - Windows 上的 TCP 窗口缩放

c - C 中的 while 循环求阶乘

c - 修改作为函数传入的字符串文字

c - 如何在不知道字符串和字符大小的情况下动态创建C中的字符串数组?

c++ - 我可以对宏使用哪些技巧?