C中的Readline函数输出奇怪的结果

C中的Readline函数输出奇怪的结果,c,linux,shell,gnu,readline,C,Linux,Shell,Gnu,Readline,我正在尝试使用GNU Readline库在shell中实现自动完成和历史记录。我使用fgets()检索用户,在阅读了readline函数的工作原理后,我决定使用它以支持自动完成等。但是当我执行程序时,readline函数在我输入任何内容之前在shell上输出奇怪的字符。奇怪的结果,如P�6,PJ�`,P�#,P�s`。出于某种原因,它总是以P开头。以下是我的代码: int main(int argc, char* argv[]) { char *historic, userInput[1000

我正在尝试使用GNU Readline库在shell中实现自动完成和历史记录。我使用
fgets()
检索用户,在阅读了
readline
函数的工作原理后,我决定使用它以支持自动完成等。但是当我执行程序时,
readline
函数在我输入任何内容之前在shell上输出奇怪的字符。奇怪的结果,如
P�6
PJ�
`,
P�#<代码>,
P�s`。出于某种原因,它总是以P开头。以下是我的代码:

int main(int argc, char* argv[]) {

char *historic, userInput[1000];
static char **cmdArgv;/**The argv of the main*/

sa.sa_handler = handle_signal;
sigaction(SIGINT, &sa, NULL);
sa.sa_flags = SA_RESTART; /** Restart function incase it's interrupted by handler */
cmdArgv = malloc(sizeof (*cmdArgv));
welcomeScreen();//just printf's nothing special
while(TRUE)
{
    shellPrompt();// getcwd function
    historic = readline(userInput);
    if (!historic)
        break;
     //path autocompletion when tabulation hit
    rl_bind_key('\t', rl_complete);
     //adding the previous input into history
    add_history(historic);    
    if( check_syntax(userInput) == 0 ){
        createVariable(userInput);
    }

    else{
        tokenize(cmdArgv, userInput);
        special_chars(cmdArgv);
        executeCommands(cmdArgv, userInput);
    }
}

你知道问题出在哪里吗?谢谢。

在将
用户输入传递到
readLine()之前,先初始化
用户输入:

这是对传递给
readLine()
函数(我在这里找到)的参数的描述:

如果参数为NULL或空字符串,则不会发出提示


由于您没有初始化
userInput
,因此它正在显示发生在其中的任何内容。

@hjmd:谢谢,它工作正常。但是为什么我必须在我的案例中设置userInput?我在readline上阅读了很多教程,但没有一本是这样做的。@hjmd:刚刚看到了你编辑过的答案。谢谢仍然让我困惑的是,为什么没有教程提到它。我看到的示例使用了
sprintf()
或类似的方法来填充
readLine
的参数,该参数将填充以null结尾的字符串,并显示一些合理的内容。试着用一些东西填充它来见证这种行为。例如,在
memset()
调用do
userInput[0]='$'之后应该会显示一个美元提示。没错,教程使用了
sprintf()
或类似的函数。我试过你的例子。。。。我现在明白了<仅声明了代码>用户输入
。所以它包含随机字符。所以它展示了那里的一切。谢谢你的帮助:)
memset(userInput, 0, sizeof(userInput));