มีโปรแกรมรันอยู่ก่อนแล้ว ผมก็เปิดอีก terminal นึงแล้วเอา GDB เสียบไปที่ process id ที่รันอยู่
$ ./example.o
Put string to split: hello world
First str: Hello
Second str: World
Put string to split:
$ sudo gdb ./example.o -p `pgrep example.o`
0x00007f474d3a8081 in __GI___libc_read (fd=0, buf=0x55beb275a670, nbytes=1024)
at ../sysdeps/unix/sysv/linux/read.c:27
27 ../sysdeps/unix/sysv/linux/read.c: No such file or directory.
(gdb)
เรารู้ว่ามันจะตายถ้า user ใส่ string ก้อนเดียว จากนั้นก็ดูโค้ดเราว่ามันควรแก้ตรงไหนบ้างเพื่อให้ไม่ตาย
6 char** split(char* input) {
7 char** result = malloc(10*sizeof(char*));
8 result[0] = input;
9 int j = 1;
(gdb) b example.c:8
Breakpoint 1 at 0x55beb209d875: file example.c, line 8.
(gdb) commands
Type commands for breakpoint(s) 1, one per line.
End with a line saying just "end".
>set var result = calloc(10*sizeof(char*),1)
>continue
>end
(gdb) b example.c:28 if result[1] == 0
Breakpoint 2 at 0x55beb209d995: file example.c, line 28.
(gdb) commands
Type commands for breakpoint(s) 2, one per line.
End with a line saying just "end".
>jump example.c:29
>continue
>end
(gdb) c
Continuing.
Put string to split: helloworld
First str: Helloworld
Second str: (null)
Put string to split: helloworld
First str: Helloworld
Second str: (null)
Put string to split: test
First str: Test
Second str: (null)
Put string to split: a
First str: A
Put string to split: hello world
First str: Hello
Second str: World