Bartc said:
[advocating debuggers]
In this case he could use printfs etc til the cows came home and
still not have clue where the crash happened.
run
bt
I've never used a debugger, ever, but I thought I'd give this a go.
First problem was to get gdb for Windows, but 10-15 mins on google and
no luck (all those .tar.gz files I kept seeing did not look
promising). But then I found gdb.exe as part of my dev-c++ (which I
rarely use).
Then, it kept saying 'no debugging symbols found' no matter what -g3
or -ggdb switches I use for gcc. Until I tried:
gcc -g3 -o c c.c
as suggested by the tutorial (although it didn't explain what -o
filename does) which fixed that.
The -o switch instructs gcc to place it's output in a file whose name is
specified as an argument to the switch. Otherwise the output file is
named according to certain defaults. From the gcc manual:
---------
-o FILE'
Place output in file FILE. This applies regardless to whatever
sort of output is being produced, whether it be an executable file,
an object file, an assembler file or preprocessed C code.
If `-o' is not specified, the default is to put an executable file
in `a.out', the object file for `SOURCE.SUFFIX' in `SOURCE.o', its
assembler file in `SOURCE.s', a precompiled header file in
`SOURCE.SUFFIX.gch', and all preprocessed C source on standard
output.
---------
Now for a program that crashes:
#include <stdio.h>
int main(void) {
char *p=0;
puts(p);
}
Without a debugger I anyway get a report telling me at want address it
went wrong (and if that address is in my program, I can use dumppe to
find the approximate place -- this is for Windows).
With dbg, I get this:
(gdb) bt
#0 0x77c41908 in _end__ ()
Cannot access memory at address 0x406000
My session is:
$ gdb ./a.out
GNU gdb 6.4-debian
Copyright 2005 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you
are welcome to change it and/or distribute copies of it under certain
conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for
details.
This GDB was configured as "i486-linux-gnu"...Using host libthread_db
library "/lib/tls/i686/cmov/libthread_db.so.1".
(gdb) run
Starting program: /home/santosh/tmp/a.out
Program received signal SIGSEGV, Segmentation fault.
0xb7e432a3 in strlen () from /lib/tls/i686/cmov/libc.so.6
(gdb) where
#0 0xb7e432a3 in strlen () from /lib/tls/i686/cmov/libc.so.6
#1 0xb7e2e9bc in puts () from /lib/tls/i686/cmov/libc.so.6
#2 0x08048383 in main () at 2.c:5
(gdb)
So gdb clearly indicates where the fault occurred - in the strlen
function, which was called from puts, which was called from line five
in the main function.