gcc -g -std=c11 -o reverse reverse2.c gdb ./reverse Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later 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 "x86_64-redhat-linux-gnu". For bug reporting instructions, please see: ... Reading symbols from /homes/bdmyers/cse374_demos/11/reverse...done. # Our very coarse hypothesis is that the bug occurs in reverse, # so we turn that hypothesis into a breakpoint on the call to reverse. # Then we run the program. (gdb) break reverse Breakpoint 1 at 0x4006ec: file reverse2.c, line 21. (gdb) run Starting program: /homes/bdmyers/cse374_demos/11/./reverse Please enter a string: 1234 Breakpoint 1, reverse (s=0x7fffffffe440 "1234\n") at reverse2.c:21 21 char * result = NULL; /* the reversed string */ Missing separate debuginfos, use: debuginfo-install glibc-2.17-20.fc19.x86_64 (gdb) step # dereference a pointer with x. Before the malloc statement # executes, result is just 0x0 (null). 26 result = (char *) malloc(strlen(s)+1); (gdb) x result 0x0: Cannot access memory at address 0x0 (gdb) step # after malloc is called, dereferencing our valid # address gives us unintialized data. 29 strcpy(result,s); (gdb) x result 0x602010: 0x00000000 (gdb) x /c result 0x602010: 0 '\000' (gdb) x /c result 0x602010: 0 '\000' 0 '\000' 0 '\000' 0 '\000' 0 '\000' 0 '\000' 0 '\000' 0 '\000' 0x602018: 0 '\000' 0 '\000' (gdb) step # after the string copy, the char array pointed to by result # is now set to a copy of the input data. 31 L = 0; (gdb) stepx /10c result 0x602010: 49 '1' 50 '2' 51 '3' 52 '4' 10 '\n' 0 '\000' 0 '\000' 0 '\000' 0x602018: 0 '\000' 0 '\000' # we continue, to the end of the first swap operation # to see how result changes (gdb) step 32 R = strlen(result); (gdb) step 34 while (L < R) { (gdb) step 35 ch = result[L]; (gdb) stpep 36 result[L] = result[R]; (gdb) step 37 result[R] = ch; (gdb) step # we peek at result again and find that the first character '1' # got swapped with the null terminator. That's our bug! # we fix it in reverse3.c 38 L++; R--; (gdb) x /10c result 0x602010: 0 '\000' 50 '2' 51 '3' 52 '4' 10 '\n' 49 '1' 0 '\000' 0 '\000' 0x602018: 0 '\000' 0 '\000' (gdb) x /10cs 0x7fffffffe440: 49 '1' 50 '2' 51 '3' 52 '4' 10 '\n' 0 '\000' 0 '\000' 0 '\000' 0x7fffffffe448: -48 '\320' -28 '\344' (gdb) quit A debugging session is active. Inferior 1 [process 19824] will be killed. Quit anyway? (y or n) y bash-4.2$ exit exit Script done on Wed 04 Feb 2015 02:22:25 PM PST