Allocating memory for a array to char pointer
        Posted  
        
            by nunos
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by nunos
        
        
        
        Published on 2010-05-25T18:29:49Z
        Indexed on 
            2010/05/25
            18:31 UTC
        
        
        Read the original article
        Hit count: 228
        
The following piece of code gives a segmentation fault when allocating memory for the last arg. What am I doing wrong? Thanks.
    int n_args = 0, i = 0;
    while (line[i] != '\0')
    {
        if (isspace(line[i++]))
            n_args++;
    }
    for (i = 0; i < n_args; i++)
        command = malloc (n_args * sizeof(char*));
    char* arg = NULL;
    arg = strtok(line, " \n");
    while (arg != NULL)
    {
        arg = strtok(NULL, " \n");
            command[i] = malloc ( (strlen(arg)+1) * sizeof(char) );
        strcpy(command[i], arg);
        i++;
    }
Thanks.
© Stack Overflow or respective owner