未初始化的值是由堆栈分配创建的 [英] Uninitialised value was created by a stack allocation

查看:23
本文介绍了未初始化的值是由堆栈分配创建的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

==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)

被引用的行:

int limit = atoi(argv[1]);

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

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

代码(来自修订历史):

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;
}

推荐答案

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

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

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

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]; }

这篇关于未初始化的值是由堆栈分配创建的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆