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



我有一个函数,它接受一个字符串数组。它通过特定字符的存在来分隔所有这些字符串,在本例中为"|"。请参阅我之前的问题以获得更好的想法基于字符拆分字符串数组

所以,我有一个字符串数组,看起来像这样:

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

我的parseCmds函数应该遍历数组中的每个字符串,并创建一个新的字符串数组,其中所有字符串都在"|"字符之前。然后,它创建了一个链表,其中每个节点都指向我创建的字符串数组中的每一个,基本上将原始字符串数组分离为彼此链接的单独字符串数组。

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

在第一次迭代时: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

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

在本语句中,您还没有为cmnd指针(字符串)分配内存。我相信这可能是你问题的部分原因。您已经为结构分配了内存,但还需要为结构中的每个指针分配内存。

最新更新