chacham15
chacham15

Reputation: 14281

Valgrind reports silly arg to malloc, how do I find out where?

I get a warning when running my program under valgrind:

==24214== Warning: silly arg (-1) to malloc()

How can I determine what call to malloc() is faulty? Is there a way I can do this without recompiling?

The program is compiled with -g (debug) and without -s (strip).

Upvotes: 1

Views: 1115

Answers (5)

chacham15
chacham15

Reputation: 14281

I ended up inserting printf's and finding if it came before or after the valgrind printf. Less fancy than what you guys reccomended, but it worked faster than trying to implement the other solutions.

Upvotes: 0

Kaz
Kaz

Reputation: 58627

Indeed, it appears that valgrind refuses to print a stack trace for this situation, even with --verbose. Please write to the mailing list; there should be an option for this otherwise the diagnostic isn't that helpful.

Note that the argument of malloc is an unsigned type, size_t, which does not have -1 in its range. What this situation means is actually that the largest possible value of size_t was passed to malloc.

Strictly speaking, that is not an erroneous API call, but it does probably indicate that something is wrong. (Your program does not need multi-gigabyte arrays, right?)

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 754790

After a modicum of experimentation on a relatively antique RedHat Linux with Valgrind version 3.2.1, it appears that it does not produce a more precise warning. Further, even Valgrind 3.7.0 on Mac OS X 10.7.3 doesn't do a better job of identifying the erroneous call.

Test code:

#include <stdlib.h>
#include <stdint.h>
int main(void)
{
    int   l = -1;
    char *x = malloc(l);
    return (uintptr_t)x & 1;
}

So, since valgrind does not help, you are probably reduced to using the debugger on the program, breaking on calls to malloc() — perhaps conditionally breaking when the argument is equal to (size_t)-1.

Upvotes: 1

Alan
Alan

Reputation: 151

You might find where that text "silly arg" gets called inside valgrind. Bring up your debugger and break on that spot. Run your program and when it brings you back to the debugger prompt go up until you're at the line that called the malloc.

Upvotes: 0

Soren
Soren

Reputation: 14708

you can do a break point on malloc and make it conditional, for example that the arg is <0

Upvotes: 0

Related Questions