Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you debug a C program on Windows?

I've never used a debugger and the time has come to give them a try. MinGW appears to come with GDB which I've been trying to use. Supposdly running gdb from the command line and typing run myprog.exe starts the debugger but when I do this I get

Starting program: C:\MinGW\bin\myprog.exe MyProg.exe [New Thread 1828.0xd8c] Error opening file. [Inferior 1 (process 1828) exited with code 02]

How to proceed or what's an easier way?

In particular I'm trying to flush out undefined behavior.

like image 249
Celeritas Avatar asked Oct 04 '13 08:10

Celeritas


3 Answers

Since your program terminates, you'll need to set a breakpoint to see anything. Try break main before the run line. Then you can do commands line next (next line), step (step into/outof function calls), print expression (where expression can be a variable name or a function-call or a calculation), display expression (same as print, but prints just before each prompt). At any given point you can type backtrace to get a call stack. You can even type up and down to move up the callstack, so you can print higher local variables.

like image 120
luser droog Avatar answered Sep 28 '22 07:09

luser droog


Well, the easiest way would be to use an IDE, actually. You might want to give code::blocks a try - very easy to use, configures everything for you on installation (just make sure to pick a compiler - don't worry, it'll prompt you) and there, you're all set and ready to go. As it's multi-platform, it doesn't really lock you into windows either, and gives you very powerful (and, I guess more importantly, convenient) possibilities of graphical debugging.

like image 37
Fenixp Avatar answered Sep 28 '22 06:09

Fenixp


pass the binary with gdb

gdb <binary>

then set breakpoint to main

gdb) break main

Then run your program in gdb

gdb) run

then break point hits use 'n' or 'next' to step to different lines

gdb) n

Use 's' for stepping into function and 'p' printing var value

Example :

gdb) s <fun_name> 
gdb) p x 
like image 37
Sohil Omer Avatar answered Sep 28 '22 06:09

Sohil Omer