Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uninitialised value was created by a stack allocation

Tags:

c

valgrind

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

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;
}
like image 869
Eduardo Bautista Avatar asked Feb 24 '13 05:02

Eduardo Bautista


1 Answers

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

like image 165
autistic Avatar answered Nov 15 '22 12:11

autistic