c++clang++

Why does this program trap, kill or result in a segmentation fault?


Platform: aarch64, android 14, clang 20.1.6 (latest version), llvm 20.1.6, kernel 5.4.254-qgki-ga443

Code:

int start_game(void) {
}

int main(int argc, char **argv) {
    start_game();
}

Problem: My code results in this output

zsh: trace trap  ./src/main

When I change 'int' to 'void' on line 1, program behaves normally.

Running with 'sh' does not solve the problem, program still ends with 'SIGTRAP'.

I tried compiling with '-O0', '-O1', '-O2' and '-O3'. The results are same, except that with '-O1' or higher, the program exits with 'SIGKILL'.

Compilation command:

clang++ -o src/main src/main.cpp
./src/main

When I compile this as a C file, on '-O0' it exits with 'SIGTRAP', on '-O1' and higher it exits with 'SIGSEGV' (Segmentation fault).


Solution

  • Since start_game returns int, it must have a return statement to return a value. Falling off the end of a non-void function causes undefined behavior.

    Note that in C++, this is true even if the calling function does not use the return value. The rule in C is different; see https://stackoverflow.com/a/69008261/634919