Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was trying to parse a shell command so I can execute it with my own shell:

C#
cp = (strtok(command, hash));            //Get the initial string (the command)
parameter[0] = (char*) malloc(strlen(cp)+ 1);                     //Allocate some space to the first element in the array
strncpy(parameter[0], cp, strlen(cp)+ 1);
for(i = 1; i < MAX_ARG; i++)
{
    cp = strtok(NULL, hash);                 //Check for each string in the array
    parameter[i] = (char*) malloc(strlen(cp)+ 1);
    strncpy(parameter[i], cp, strlen(cp)+ 1);                      //Store the result string in an indexed off array
    if(parameter[i]  == NULL)
    {
        break;
    }
    if(strcmp(parameter[i], "|") == 0)
    {
        cp = strtok(NULL, hash);
        parameter2[0] = (char*) malloc(strlen(cp)+ 1);
        strncpy(parameter2[0], cp, strlen(cp)+ 1);
        //Find the second set of commands and parameters
        for (j = 1; j < MAX_ARG; j++)
        {
            cp = strtok(NULL, hash);
            if (strlen(cp) == NULL)
            {
                break;
            }
            parameter2[j] = (char*) malloc(strlen(cp)+ 1);
            strncpy(parameter2[j], cp, strlen(cp)+ 1);
        }
        break;
    }


This portion is supposed to store the command and parameters in their corresponding arrays. However, if it sees a " | (a pipe) ", its suppose to enter store the second set of command parameter properly. When I run this code I get an error when I do strlen(cp) == NULL
Posted
Updated 19-Oct-11 23:05pm
v2
Comments
Mehdi Gholam 20-Oct-11 5:06am    
EDIT -> removed extra formatting

1 solution

strtok() returns a pointer to the next token or NULL. If it returns NULL then the call to strlen() will fail because you have passed it an invalid pointer. Your code should read:
C++
cp = strtok(NULL, hash);
if (cp == NULL)

Note that you have similar bugs elsewhere in your code; you must check that the return from strtok() is non-null before passing it to any other function.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900