ohiohai
ohiohai

Reputation: 73

Add list of Strings to LinkedList

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.

Upvotes: 2

Views: 40

Answers (1)

eyalm
eyalm

Reputation: 3366

There are a few problems.

You must initialize the head of the list:

NODES nodes = NULL;

You did not allocate the args array:

(*nodes)->args = malloc(sizeof(char *)*nArgs)

If you want to be sure where the crash is, use a debugger:

# gdb ./prog
(gdb) run

Program received signal SIGSEGV, Segmentation fault.
0x00000000004006e9 in insert (nodes=0x7fffffffdc98, idNode=1, 
    cmdNode=0x40088f "wc", argsNode=0x7fffffffdca0, nArgs=4, conn=0) at    qq.c:33
33                  (*nodes)->args[i]=strdup(argsNode[i]); 

After the crash:

(gdb) backtrace

You will see the exact faulty line

Another thing. It is not realistic to use recursion for linked-list insertion. It will hit the stack limit pretty fast.

Upvotes: 3

Related Questions