开发者

Tokenize command line input in C

开发者 https://www.devze.com 2023-02-22 17:11 出处:网络
trying to take a line of text and tokenize it into a filename and arguments for execvp(). Here\'s my code, getArguments() is the broken function. Currently, trying to print arguments[0] results in a b

trying to take a line of text and tokenize it into a filename and arguments for execvp(). Here's my code, getArguments() is the broken function. Currently, trying to print arguments[0] results in a bus error.

char* getFilename(char* input) {
    return strtok(input, " &");
}

char** getArguments(char* input) {
    char** arguments;
    int k = 0;
    char* tokenized;
    tokenized = strtok(input, " &");
    tokenized = strtok(NULL, " &");
    while (tokenized != NULL) {
        arguments[k] = tokenized;
        ++k;
        tokenized = strtok(NULL, " &");
    }
    return arguments;
}

I am using it in the following manner later in my code:

char* filename = getFilename开发者_JAVA百科(line);
char** arguments = getArguments(line);


The call to getFilename modifies the string by placing a '\0' character after the first token. Then you attempt to restart at the beginning in getArguments. That only yields the first token since the string is now prematurely terminated. You can fix this problem by getting rid of getFilename and getting it from getArguments.

char **arguments = getArguments(line);
char *filename = arguments[0];

Also, you must allocate space for each pointer in the char **arguments; array. You can use realloc to grow the array dynamically. However, there are more efficient approaches.

char** getArguments(char* input) {
    char** arguments;
    int k = 0;
    char* tokenized;
    arguments = calloc(1, sizeof (char *));
    tokenized = strtok(input, " &");
    /* don't eat the first token here since we want the filename in arguments */
    while (tokenized != NULL) {
        arguments[k] = tokenized;
        ++k;
        arguments = realloc(arguments, sizeof (char *) * (k + 1));            
        tokenized = strtok(NULL, " &");
    }

    /* an extra NULL is required to terminate the array for execvp() */
    arguments[k] = NULL;

    return arguments;
}


You haven't allocated any memory for char **arguments - it's just a dangling pointer.


char **arguments is a single pointer. Consider where it points....

Hint: it should point somewhere useful where it can hold multiple pointers.

0

精彩评论

暂无评论...
验证码 换一张
取 消