c - 未初始化的值是由堆栈分配创建的 - 无法找到我出错的地方

标签 c initialization valgrind

int main(){

char *input = NULL;
char *line[2048];
size_t inputChars = 0;
size_t bufferSize = 0;

char *command = NULL;
char *arguments[2048];

printf(":");
fflush(stdout);


while((inputChars = getline(&input , &bufferSize , stdin)) > 0){

    memset(line, '\0' , (sizeof *line * sizeof line[0]) );
    memset(arguments, '\0' , (sizeof *arguments * sizeof arguments[0]));

    if(inputChars == -1){

        clearerr(stdin);
    }
    else{
        parseLine(input,line);

        command = line[0];

        int i = 0;
        int j = 1;

        while(line[j] != NULL)
        {
            arguments[i] = line[j];
            i++;
            j++;
        }

        if((*line[0] != '#') && (*line[0] != '\n'))
        {
            runCommand(command,arguments);
        }


        printf(":");
        fflush(stdout);

    }

    input = NULL;
  }
}
int isBackground(char* args[])
{
    int i = 0;
    int pos = 0;
    while (args[i] != NULL)
    {
        pos++;
        i++;
    }
    if (*args[pos - 1] == '&')
    {
        background++;
        return true;
    }
    else return false;
}

void runCommand(char* cmd, char* args[])
{
    printCommandLine(cmd, args);

    if (isBackground(args))
    {
        printf("Background Processes: %i\n",background);

    }
}

void printCommandLine(char* cmd, char* args[])
{

    printf("Command: %s\n",cmd);

    printf("Arguments:\n");

    int i = 0;

    while (args[i] != NULL)
    {
        printf("%s\n",args[i]);
        i++;
    }
}

Valigrind 结果:

Valgrind Results

xcode 输出:

xcode output

我找不到哪里出错了。我正在为可以接受带有参数列表的命令的命令行编写一些简单的代码。该程序对于长度 <= 7 的字符串数组运行良好,并且在第一次输入此大小的命令后适用于每个命令数组。我不知道我在哪里使用未初始化的值。当代码中断时,我在遍历参数数组时无法访问。我怀疑这可能与填充参数数组的 main 中的 while 循环有关,但我可能错了。真的坚持这一点。感谢您的帮助或建议,如果您有任何想法。

最佳答案

memset(arguments, '\0' , (sizeof *arguments * sizeof arguments[0]))

这是您的代码导致未初始化值的问题。

*argumentsarguments[0] 相同。 sizeof 都是 sizeof(char*)

这意味着您只初始化缓冲区中的几个条目。

你需要

memset(arguments, '\0', sizeof(arguments));

上一行也是如此

memset(line, '\0', sizeof(line));

关于c - 未初始化的值是由堆栈分配创建的 - 无法找到我出错的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45497380/

相关文章:

c - 在地址中使用先前参数时 Sscanf 未初始化的值

c - C语言中如何将字符串转换为整数?

c - 使用 cblas_sgemm 执行复杂的矩阵操作以进行乘法

在初始化程序中快速复制属性

Spring用主机名初始化bean

perl - 如何将 valgrind 输出转换为 XML?

c - Valgrind 错误 : invalid write of size 4 (but says error is in free() )

c - 为什么我的 Collat​​z 序列 C 程序不打印最终值 (1)?

c++ - 我在 Linux C 或 C++ 中搜索 Windows msg.exe 的等效项

java - 为什么重复使用扫描仪直到用户输入合法值后会出现 "variable might not have been initialized "错误?