用C编程Shell,消失的char **传递给函数时

时间:2015-08-22 23:10:41

标签: c shell pointers malloc

我只找到了这样的几个主题,没有一个我能够理解的信息。我正在用C语言编写一个shell,我觉得它应该很简单,但我的C编程并不那么新鲜。我遇到了传递双指针和内容消失的问题

我觉得我在正确的轨道上,听起来它与初始化有关,但我尝试了一些事情,设置指针指向NULL只是为了确定。感谢。

void runProgram (char **cLine);
char **parse(char *str);

/*
 * 
 */
int main(int argc, char** argv) 
{
    char *cin = NULL;
    ssize_t buffer = 0;
    char **tempArgs = NULL;
    printf(">");

    while(1)
    {
        getline(&cin, &buffer, stdin);
        tempArgs = parse(cin);  //malloc, parse, and return
        printf("passing %s", tempArgs[0]);  //works just fine here, can see the string
        runProgram(tempArgs); //enter this function and array is lost
    }
    return (EXIT_SUCCESS);
}
char** parse( char* str )
{
    char *token = NULL;
    char tokens[256];
    char** args = malloc( 256 );    
    int i = 0;

    strcpy( tokens, str );

    args[i] = strtok( tokens, " " );

    while( args[i] )
    {

        i++;
        args[i] = strtok(NULL, " ");
    }
    args[i] = NULL;

    return args;
}

在此函数调用

之前可见
void runProgram (char **cLine)
{
   //function that calls fork and execvp
}

1 个答案:

答案 0 :(得分:1)

最简单的解决方法是在tokens函数中根本不使用parse()

int main(void) 
{
    char  *buffer = NULL;
    size_t buflen = 0;
    char **tempArgs = NULL;

    printf("> ");

    while (getline(&buffer, &buflen, stdin) != -1)
    {
        tempArgs = parse(buffer);
        printf("passing %s", tempArgs[0]);
        runProgram(tempArgs);
        printf("> ");
        free(tempArgs);  // Free the space allocated by parse()
    }
    free(buffer);        // Free the space allocated by getline()
    return (EXIT_SUCCESS);
}

char **parse(char *str)
{
    char **args = malloc(256); 
    if (args == 0)
        …handle error appropriately…   
    int i = 0;

    args[i] = strtok(str, " ");

    // Bounds checking omitted
    while (args[i])
        args[++i] = strtok(NULL, " ");

    return args;
}

请注意,当循环终止时,数组已经为空终止,因此不需要额外的赋值(但最好是安全而不是抱歉)。