Valgrind swears at malloc ()

Language C, program:

#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { long n, x, *args; scanf("%d", &n); args = (long*)malloc(n * sizeof(long)); if(!args) { printf("Allocation error\n"); return -1; } free(args); return 0; } 


This code after entering a variable in valgrind gives the following error:

 ==27041== Conditional jump or move depends on uninitialised value(s) ==27041== at 0x4C2CE0C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) 


Experiencedly found that the error appears only when I add the variable n to malloc. That is, for example, malloc (sizeof (long) * 5); it works without errors, but if the constant "5" is replaced with the variable n, valgrind starts swearing.

Why can this happen and what alternative is there?

ZY If you do not let the program through the debugger, then it works absolutely adequately.

  • Indeed, the definition helped, thanks. - cryptostimor

1 answer 1

You read a variable n type long using the %d format in scanf . Not surprisingly, the result is rubbish. The %d format is read-only int . To read long values, you need the format %ld .

(Did the compiler, by the way, warn you about the wrong format? Or did you just ignore the warning?)

On your platform, the long type is obviously wider than the int type, which in practice leads to the fact that due to an incorrect format in scanf value n "initialized" only partially. That's about it and you trumpet valgrind.

To treat this problem by pre-zeroing n is to sweep up the problem under the carpet. It is a good idea to initialize variables in front of scanf , but this is not the essence of the error.

  • Thanks for the detailed answer, now everything is clear. In fact, changing the format to% ld solved not only this problem, but also the problem with the output in printf. The compiler, by the way, was silent about this problem. - cryptostimor