C语言 未初始化的值是由堆栈分配创建的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15049033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:25:32  来源:igfitidea点击:

Uninitialised value was created by a stack allocation

cvalgrind

提问by Eduardo Bautista

==13890== Conditional jump or move depends on uninitialised value(s)
==13890==    at 0x4E7E4F1: vfprintf (vfprintf.c:1629)
==13890==    by 0x4E878D8: printf (printf.c:35)
==13890==    by 0x400729: main (001.c:30)
==13890==  Uninitialised value was created by a stack allocation
==13890==    at 0x400617: main (001.c:11)

The line being referenced:

被引用的行:

int limit = atoi(argv[1]);

I am not sure how to fix it. I have tried searching on stackoverflow and google but I could not find the solution.

我不知道如何解决它。我尝试在 stackoverflow 和 google 上搜索,但找不到解决方案。

The code (from revision history):

代码(来自修订历史):

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    if (argc != 2) {
        printf("You must pass a single integer\n");
        exit(1);
    }

    int limit = atoi(argv[1]); 
    int numbers[limit / 2];
    int count = 0;
    int i;
    for (i = 3; i < limit; i++) {
        if (i % 3 == 0 || i % 5 == 0) {
            numbers[count] = i;
            count++;
        }
    }

    int sum = 0;

    for (i = 0; i < count; i++) {
        sum += numbers[i];
    }

    printf("The sum is: %d\n", sum);

    return 0;
}

回答by autistic

Have you checked argcand the contents of argv[1]? Is argv[1]guaranteed to be non-NULLin order to be suitable as input for atoi? Is it possible that atoimight be returning a trap representation representing an uninitialised value, due to argv[1]being non-numeric?

你检查过argc和 的内容argv[1]吗?是否argv[1]保证是非NULL以适合作为输入atoiatoi由于argv[1]非数字,是否有可能返回表示未初始化值的陷阱表示?

edit: After seeing the complete code, I've realised that that's not the problem, and your diagnosis is incorrect. Your problem is here: for (i = 0; i <= count; i++) { sum += numbers[i]; }Wheni == count, numbers[i]is uninitialised. This is because count is incremented after the last assignment to numbers[count]in the previous loop: numbers[count] = i; count++;. Hence, printing sum results in your message because sum itself depends upon an uninitialised value. Perhaps you meant for (i = 0; i < count; i++) { sum += numbers[i]; }

编辑:看到完整的代码后,我意识到这不是问题,你的诊断是不正确的。您的问题在这里:for (i = 0; i <= count; i++) { sum += numbers[i]; }When i == count,numbers[i]未初始化。这是因为 countnumbers[count]在上一个循环中最后一次赋值后递增:numbers[count] = i; count++;。因此,打印 sum 会导致您的消息,因为 sum 本身取决于未初始化的值。也许你的意思是for (i = 0; i < count; i++) { sum += numbers[i]; }

回答by Rohit

int limit = atoi(argv[1]) Declare it first with init value and then use it.

int limit = atoi(argv[1]) 先用init值声明然后再使用。