4

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?

Nghia
  • 111
  • 2
  • 9

2 Answers2

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.

ks1322
  • 33,961
  • 14
  • 109
  • 164
0

-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.

  • Just what I was looking for! I tend to avoid Valgrind simply because I don't have the patience to wait around for it to find the fault. By default, my program feels like it's 100x slower. – Nghia Nov 10 '11 at 22:07
  • 1
    Stack-protector imposes certain overhead as well, but it's likely much less noticeable than valgrind's. However, stack-protector itself, as the name suggests, only covers problems with object allocated on stack and not on the heap. However, I've just thought that you may also use special allocator for heap error checking, which may impose less overhead than valgrind. See dmalloc (http://dmalloc.com/) and libxalloc (http://shh.thathost.com/pub-unix/#xalloc) –  Nov 11 '11 at 11:40