This C function should always return false, but it doesn’t

后端 未结 4 1815
天命终不由人
天命终不由人 2021-01-29 18:15

I stumbled over an interesting question in a forum a long time ago and I want to know the answer.

Consider the following C function:

f1.c

#incl         


        
4条回答
  •  深忆病人
    2021-01-29 18:24

    You don't have a prototype declared for f1() in main.c, so it is implicitly defined as int f1(), meaning it is a function that takes an unknown number of arguments and returns an int.

    If int and bool are of different sizes, this will result in undefined behavior. For example, on my machine, int is 4 bytes and bool is one byte. Since the function is defined to return bool, it puts one byte on the stack when it returns. However, since it's implicitly declared to return int from main.c, the calling function will try to read 4 bytes from the stack.

    The default compilers options in gcc won't tell you that it's doing this. But if you compile with -Wall -Wextra, you'll get this:

    main.c: In function ‘main’:
    main.c:6: warning: implicit declaration of function ‘f1’
    

    To fix this, add a declaration for f1 in main.c, before main:

    bool f1(void);
    

    Note that the argument list is explicitly set to void, which tells the compiler the function takes no arguments, as opposed to an empty parameter list which means an unknown number of arguments. The definition f1 in f1.c should also be changed to reflect this.

提交回复
热议问题