I'm trying to implement a linked list but i'm having some trouble when it comes to add an array of strings to it. It adds the first time with no trouble, but if i call my insert function again I get a "Segmentation fault: 11" error.
Here's the code:
typedef struct node_s{
int id;
char *cmd;
char **args;
int numArgs;
int connected;
struct node_s *next;
}node;
typedef node *NODES;
void insert(NODES *nodes, int idNode, char *cmdNode,char **argsNode, int nArgs,int conn){
int i;
if (!exist(*nodes,idNode))
{
if(*nodes==NULL){
*nodes = (NODES) malloc(sizeof(struct node_s));
if(*nodes==NULL)
{
perror("malloc err");
return;
}
(*nodes)->id = idNode;
(*nodes)->cmd = strdup(cmdNode);
// Problem
for(i=0;i<nArgs;i++)
(*nodes)->args[i]=strdup(argsNode[i]);
(*nodes)->numArgs=nArgs;
(*nodes)->connected=conn;
(*nodes)->next = NULL;
}
else
insert(&(*nodes)->next,idNode,cmdNode,argsNode,nArgs,conn);
}
}
int main()
{
char *cmds[4]={"wc", "-l", "another","hello.com"};
NODES nodes;
inicNodes(&nodes);
insert(&nodes,1,"wc",cmds,4,0);
// if i try to list my values here it shows them as expected.
insert(&nodes,3,"ls",cmds,4,1);
return 0;
}
Thank you.
(*nodes)->args[i]=strdup(argsNode[i]);- invokes undefined behavior. You forgot to allocate the pointer bed forargs.(*nodes)->args = malloc(nArgs * sizeof(char*));is missing.