GCC flags to improve run-time error catching?

2019-08-13 19:43发布

问题:

I've recently ported a Linux C++ application to Windows (via Visual Studio 2010 C++ express). In the process I've noticed the Windows executable tends to pick up on subtle bugs in my code, crashing the program. But the same code and bug seems to go unnoticed in Linux/GCC and the program will continue running happily. I've seen this behaviour in past programs I tried to port. An example bug in my code is writing pass an array by 1 element.

What flags can I enable to improve run-time error catching in GCC? I want my program to be as volatile as the Windows version when it encounters the slightest run-time bug. Or does this depend more on the OS and is out of the user's control?

回答1:

An example bug in my code is writing pass an array by 1 element.

Bugs like this are usually easily detected by Valgrind. I would suggest you to check your code under Valgrind always when you suspect bugs like this - it will save a lot of time during debugging.



回答2:

-fstack-protector-all + valgrind is probably what you need. The former helps to fine stack corruptions:

$ cat 1.c
int main() {
    char data[10];
    int x;
    data[10] = 'x';
    return 0;
}
$ gcc 1.c && ./a.out    
$ gcc -fstack-protector-all 1.c && ./a.out
Abort trap

the latter checks for heap problems.