I've encountered some weird gcc warning in my project. Let's look at this simple example in 3 files:
typedef struct {
int a;
long b;
char *c;
} myStruct;
#include <stdio.h>
#include <stdlib.h>
#include "struct.h"
myStruct* func() {
myStruct* new = (myStruct*) malloc(sizeof(myStruct));
new->a = 42;
new->b = 84;
new->c = "lol_ok\n";
return new;
}
void prn(myStruct* x) {
printf("%d\n", x->a);
}
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include "struct.h"
int main() {
myStruct* ms = func();
prn(ms);
return 0;
}
So I get the following warning:
main.c: In function ‘main’:
main.c:8:24: warning: initialization makes pointer from integer without a cast
myStruct* ms = func();
Moreover when I build it with -Wall -Wextra I get more:
main.c: In function ‘main’:
main.c:8:9: warning: implicit declaration of function ‘func’ [-Wimplicit-function-declaration]
myStruct* ms = func();
^
main.c:8:24: warning: initialization makes pointer from integer without a cast
myStruct* ms = func();
^
main.c:9:2: warning: implicit declaration of function ‘prn’ [-Wimplicit-function-declaration]
prn(ms);
What does it all mean? It also crashes if built with -fsanitize=undefined -fsanitize=address and that's weird. Why?
Lack of prototype.
Include the prototype for func() in struct.h.
myStruct* func(void);
When there's no prototype visible for func(), compiler assumes (pre-C99) that it returns an int. But func() actually returns an myStruct*.
Note that this implicit int rule has been removed from C99. So technically, your code is ill-formed in C99 and C11.
Increasing your warning level would help. gcc provides an option to catch this:
-Wimplicit-function-declaration
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