Articles

Valgrind and if statements

In Uncategorized on October 4, 2010 by Matt Giuca

Valgrind has a handy warning: “Conditional jump or move depends on uninitialised value(s)”. I discovered the other day that using if statements can help trigger this warning.

Consider this C program:

int foo()
{
    int x;
    return x;
}

int bar()
{
    return !foo();
}

int main()
{
    printf("%d\n", bar());
    return 0;
}

Note that foo returns an undefined value, and bar inverts it (returning an undefined value as well). However, this will go undetected in Valgrind, because there is no conditional jump in the generated assembly code.

Now, change bar to the following, equivalent (but more verbose) code:

int bar()
{
    if (foo())
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

The sort of code I tell my students to replace with !foo(). Yet now, Valgrind will produce the warning message “Conditional jump or move depends on uninitialised value(s)”, because now the generated code has a conditional jump (the if statement). Interesting.

Advertisements

One Response to “Valgrind and if statements”

  1. Surely given that ability, valgrind could also determine that you’re *returning* an uninitialised value? I don’t actually know how it works, but is there a good reason why it won’t / can’t?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: