0

I just encountered a very strange interaction with GCC and C that I would not have caught without -Wall:

// infer.c
#include <stdio.h>
#include <stdlib.h>

typedef struct Test {
    int dummy;
} Test;

Test* test_make() {
    Test *ret = malloc(sizeof(Test));
    ret->dummy = 1;
    // return nothing
}

int main() {
    Test* t = test_make();
    printf("%i\n", t->dummy);
}

As you can see, test_make does NOT return anything despite the return type promising a pointer to my struct.

Compiling with gcc (without warnings) results in no complaints:

gcc -o infer infer.c

And running the program produces the expected behavior:

./infer
1

I am confused at how my program ran successfully. Does GCC infer the return type of functions if there is no explicit return statement?

warning: control reaches end of non-void function [-Wreturn-type]

Compiling with -Wall clearly catches that something is up, but how does GCC let this program compile (let alone run) successfully at all?

xyzhou
  • 39
  • 1
  • 7
  • 2
    This is undefined behavior, anything can happen. By accident it happens to be returning what you want. – Barmar Feb 25 '21 at 21:05
  • GCC doesn't have to infer the type, since that' already in the declaration. I assume you're asking if it's inferring the _value_? – Mooing Duck Feb 25 '21 at 21:09
  • *but how does GCC let this program compile* - C is very pemissive and will let you shoot your own feet if you would like to. It might warn you though. – Eugene Sh. Feb 25 '21 at 21:20
  • Note that `main` is a special case and if you omit a `return` statement, it automatically returns 0. That's why you're getting a warning for `test_make` but not for `main`. – Nate Eldredge Feb 25 '21 at 21:30

0 Answers0