1
votes

I am very struggle to solve this problem. After I initializing a allocated memory, valgrind said that "conditional jump or move depends on uninitialised value".

So, here is my code.

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

typedef struct
{
    int st_a;
    int st_b;
    char st_c:
    char st_d:
} TEST_ST;

int inner_func(int *a, TEST_ST *st_a)
{
    //memset(st_a, 0, sizeof(TEST_ST));
    if(a[0] > 0)
    {
        printf("inner_func: bigger than zero\n");
    }
    else
    {
        printf("inner_func: else\n");
    }

    st_a->st_a = 1;
}

int main()
{
    int *a;
    int *b;
    TEST_ST *st_a;

    a = (int *)malloc(sizeof(int) * 10);
    b = (int *)malloc(sizeof(int) * 10);
    memset(a, 0, sizeof(int) * 10);
    //memset(b, 0, sizeof(int) * 10);

    st_a = (TEST_ST *)malloc(sizeof(TEST_ST));

    a[0] = 1;

    if(a[9] > 0)
    {
        printf("Bigger than zero\n");
    }
    else
    {
        printf("Smaller than zero or equal\n");
    }

    inner_func(b, st_a);

    free(st_a);
    free(b);
    free(a);

    return 0;
}

And here is a valgrind logs.

I don't understand why valgrind said like the first line in the picture.

Anybody can help me?

3
the posted code does not compile! amongst other things, this statement: char st_c: is terminated with a colon : rather than a semicolon ; Please correct, Do not re-type the code, rather, perform a copy and pasteuser3629249
you might want to use calloc() rather than malloc(), then the allocated memory will already be initialized to 0x00user3629249

3 Answers

5
votes

The value you're reading was not in fact initialized.

The line in question is in the function inner_func:

if(a[0] > 0)

The a is as parameter to the function, which was called like this:

inner_func(b, st_a);

So a in the function is the same as b in main. b points to memory returned by malloc, but that memory is never initialized.

Uncomment the line where you call memset on b.

0
votes

Run valgrind like this and post results i'll edit with the answer but this should pinpoint where is the error:

valgrind --tool=memcheck --track-origins=yes <program_path>
0
votes

You have assigned "char st_c:" and "char st_d:" change it to ';' instead of ':'