I'm trying to find a way to catch a programmer error in the argument for malloc in an automated code tester.
For example:
struct Pepe* p = malloc(sizeof(struct Pepe*));
This, of course, compiles without any problems. The thing is that struct Pepe has another struct of the same size inside it, therefore no problem appears during execution (nor with free).
The correct code should be:
struct Pepe* p = malloc(sizeof(struct Pepe));
Can we get a warning or something to catch this problem?
I tried -Wall and -Wextra but there was no warning.
valgrindwill catch the subsequent write outside of allocated memory (if the structure happens to be larger than a pointer), among other subtle problems such as memory leaksstruct foo *x = malloc (sizeof *x);; This will not warn you, but avoids the error altogether.