How to test your program in LINUX

  1. To see the contents of your current directory, type ls.
  2. To compile your program, type gcc -g abc.c -o abc (assuming that your source code is abc.c.) If there are any compilation errors, it will print it on the screen. If there are no compilation errors, it will create a file called abc in the same directory.
  3. To run your program, type ./abc. To run it with the sample file, type ./abc, etc.
  4. If your program crashes, then you need to debug it to find out where the crash happened. The debugger is called gdb and you can use it by typing gdb abc. In the debugger, when your program crashes, type where in order to find out what line your program crashed in. Here is an example:
fred@fredpc:~/$ gcc -g abc.c -o abc
fred@fredpc:~/$ ./abc
Segmentation fault (core dumped)
fred@fredpc:~/$ gdb abc
GNU gdb Red Hat Linux (5.3post-0.20021129.18rh)
Copyright 2003 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 "i386-redhat-linux-gnu"...
(gdb) run
Starting program: /home/fred/abc

Program received signal SIGSEGV, Segmentation fault.
0x0804850c in main () at abc.c:59
(gdb) where
#0  0x0804850c in main () at abc.c:59
#1  0x42015574 in __libc_start_main () from /lib/tls/
(gdb) list 59
while (c = fgetc(inputfile))
58      { if (isalnum(c))
59          buf[i++] = c;
60      }
buf[i] = '\0';
As you can see, the debugger showed that the crash happened on line 59. Here, the program tried to access the array buf[] out of bounds. This is a typical segmentation fault error. This is because LINUX has memory protection, so that if you attempt to access memory that doesn't belong to your program, the operating system will kill your program.

You can also type help at the (gdb) prompt to get help on how to use gdb's other commands.