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.
You can use the clang static analyzer for that. Consider the following (buggy) code:
#include <stdlib.h>
struct foo {
int a,b;
};
int main (void) {
struct foo *bar = malloc(sizeof(struct foo *));
free(bar);
}
Now you can invoke the clang static analyzer:
$ scan-build clang src.c
and get the following warning:
src.c:10:20: warning: Result of 'malloc' is converted to a pointer of type 'struct foo', which is incompatible with sizeof operand type 'struct foo *'
struct foo *bar = malloc(sizeof(struct foo *));
~~~~~~~~~~~~ ^~~~~~ ~~~~~~~~~~~~~~~~~~~~
1 warning generated.
scan-build: 1 bug found.
The clang static analyzer is bundled with many linux distributions in the package clang-tools. The homepage can be found here
You can't really resolve the warning this way if you're naming the types.
An easier solution would be to use the variable to find its size. This also alleviates any possible issues with the type of the variable changing:
struct Pepe *p = malloc(sizeof(*p));
Now if I make p an int *...
int *p = malloc(sizeof(*p));
it still works!
If you want to do it at execution time, you can build your code with the -fsanitize=address flag (assuming GCC or Clang) or you can use the Valgrind tool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With