Valgrind:条件跳跃或移动取决于未初始化的值

时间:2013-08-03 11:18:13

标签: c valgrind

我有以下名为main.c的c文件:

#include <stdio.h>
#include <string.h>

#define NUM_CHAR 20

int main(void) {
    char command_line[NUM_CHAR + 2]; /* Command line string includes the new line character ('\n') and a null character ('\0')  */
    while (1) {
        if (fgets(command_line, sizeof(command_line), stdin) == NULL) { /*This function reads up to sizeof(command_line)-1 characters, or until it encounters the new line character. The function adds '\0' to the end of the array */
            perror("Error: standard function fgets has failed");
            break;
        }

        if (command_line[sizeof(command_line) - 2] != '\n' && strlen(
                command_line) == NUM_CHAR + 1) { /*# of characters (excluding '\n') in command_line is <=num_char iff the condition takes place. */
            printf(
                    "Error: command length must be less than or equal     to %d characters\n",
                NUM_CHAR);
        while (getchar() != '\n') {
        } /* read the remaining characters */
        continue;/* continue with  while(1) loop */
        }

        printf("%s",command_line);

        if (command_line[0] == 'Q') {
            break;
        }
    }
  return 0;
}

一个名为input的文本文件,其中包含以下行:

 Quit

这是我在终端中运行valgrind后得到的(程序名称也是主要的):

student@student-VirtualBox:~/workspace/tests$ valgrind --track-origins=yes --leak-check=full ./main < input
==2649== Memcheck, a memory error detector
==2649== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==2649== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==2649== Command: ./main
==2649== 
==2649== Conditional jump or move depends on uninitialised value(s)
==2649==    at 0x8048542: main (in /home/student/workspace/tests/main)
==2649==  Uninitialised value was created by a stack allocation
==2649==    at 0x80484FA: main (in /home/student/workspace/tests/main)
==2649== 
Quit
==2649== 
==2649== HEAP SUMMARY:
==2649==     in use at exit: 0 bytes in 0 blocks
==2649==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==2649== 
==2649== All heap blocks were freed -- no leaks are possible
==2649== 
==2649== For counts of detected and suppressed errors, rerun with: -v
==2649== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 11 from 6)

顺便说一句,我编译了这个代码,优化为OFF(-O0)。 我有两个问题:

错误的原因是什么:条件跳转或移动取决于未初始化的值?

为什么valgrind不显示导致此错误的行的行号?

1 个答案:

答案 0 :(得分:2)

无法保证fgets会将sizeof(command_line)字节准确写入command_line。如果用户键入较短的字符串,请检查

command_line[sizeof(command_line) - 2] != '\n' 

将会读取command_line的一部分,该部分未经您的代码初始化或由fgets写入。

有几种方法可以解决这个问题。

您可以在取消引用strlen

的结尾之前先测试command_line
if (strlen(command_line) == NUM_CHAR + 1 &&
    command_line[sizeof(command_line) - 2] != '\n')

或者您可以在声明时初始化所有command_line

char command_line[NUM_CHAR + 2];
memset(command_line, 0, sizeof(command_line));