Search code examples
gccvalgrind

Valgrind: Conditional jump or move with "strncat"


Having this following code:

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

int main()
{
        char *a = "abc";
        int len = strlen(a);
        char *b = malloc(len + 1); // + 1 for null byte
        //strncpy(b, a, len) // Does not append null byte
        strncat(b, a, len); //should append null byte
        puts(b);
}

and runned as valgrind ./a.out:

...
==7223== Conditional jump or move depends on uninitialised value(s)
==7223==    at 0x484EBD0: strncat (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==7223==    by 0x1091FB: main (in /home/shepherd/inteli/c/test/a.out)
==7223== 
abc
...

It says conditional jump or move depends on uninitialized value(s). What does it mean and why does strncat exhibits it?

Does the program do any UB or is erroneous or why is Valgrind screaming?


Solution

  • why is Valgrind screaming?

    strncat appends to b, so it has to know strlen(b), but b does not point to a string, b[0] is uninitialized. malloc returns uninitialized memory.

    strncat finds the position of a zero byte inside the memory pointed to by b to copy the characters from a. To find the position of a zero byte in a memory region, it has to read char by char that memory region. Because b points to uninitailized memory region, strncat reading from it results in the valgrind error you are getting.

    Does the program do any UB or is erroneous

    Yes, yes.