在網上看到一個使用GDB實驗的例子,如下:
#include <stdio.h>
main ()
{
char my_string[] = "hello there";
my_print (my_string);
my_print2 (my_string);
}
void my_print (char *string)
{
printf ("The string is %s/n", string);
}
void my_print2 (char *string)
{
char *string2;
int size, i;
size = strlen (string);
string2 = (char *) malloc (size + 1);
for (i = 0; i < size; i++)
string2[size - i] = string[i];
string2[size+1] = `/0';
printf ("The string printed backward is %s/n", string2);
}
不管它叫greeting ,還是test,我就就叫它test.c
我編譯:gcc -o test test.c
期間於warning,關於strlen和malloc的
然後執行:./test
結果爲;
The string is hello there
The string printed backward is
有錯了,於是開始使用GDB來調試了。
# gdb test
GNU gdb 6.8-debian
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i486-linux-gnu"...
(gdb) file gdb
Load new symbol table from "/home/yaozhangjun/programme/gdb"? (y or n) y
Reading symbols from /home/yaozhangjun/programme/test...done.
//gdb內的輸出和在 gdb 外面運行的結果一樣
(gdb) run
Starting program: /home/yaozhangjun/programme/test
The string is hello there
The string printed backward is
Program exited with code 040.
然後開始了list,可是問題來了,第一次LIST
(gdb) list
1 init.c: No such file or directory.
in init.c
第二次LIST
(gdb)list
1 in init.c
第三次LIST
(gdb)list
1 in init.c
好傢伙,什麼也沒有。
又從網上搜得要編譯的時候 -g,以爲這下有救了,可是。。。
# gcc -g test -o test.c
gcc: test: No such file or directory
gcc: no input files
怎麼會這樣呢?
原來要這樣做 gcc -o test -g test.c 纔可以,
終於見到
(gdb) list
1 #include <stdio.h>
2 main()
3 {
4 char my_string[]="hello there";
5 my_print(my_string);
6 my_print2(my_string);
7 }
8
9 void my_print(char *string)
10 {
I love them.