Graphics Programs Reference
In-Depth Information
at the end is used as a delimiter character to tell any function that is dealing
with the string to stop operations right there. The remaining extra bytes are
just garbage and will be ignored. If a null byte is inserted in the fifth element
of the character array, only the characters Hello would be printed by the
printf() function.
Since setting each character in a character array is painstaking and
strings are used fairly often, a set of standard functions was created for string
manipulation. For example, the strcpy() function will copy a string from a
source to a destination, iterating through the source string and copying each
byte to the destination (and stopping after it copies the null termination byte).
The order of the function's arguments is similar to Intel assembly syntax:
destination first and then source. The char_array.c program can be rewritten
using strcpy() to accomplish the same thing using the string library. The
next version of the char_array program shown below includes string.h since
it uses a string function.
char_array2.c
#include <stdio.h>
#include <string.h>
int main() {
char str_a[20];
strcpy(str_a, "Hello, world!\n");
printf(str_a);
}
Let's take a look at this program with GDB. In the output below, the
compiled program is opened with GDB and breakpoints are set before, in, and
after the strcpy() call shown in bold. The debugger will pause the program at
each breakpoint, giving us a chance to examine registers and memory. The
strcpy() function's code comes from a shared library, so the breakpoint in this
function can't actually be set until the program is executed.
reader@hacking:~/booksrc $ gcc -g -o char_array2 char_array2.c
reader@hacking:~/booksrc $ gdb -q ./char_array2
Using host libthread_db library "/lib/tls/i686/cmov/libthread_db.so.1".
(gdb) list
1 #include <stdio.h>
2 #include <string.h>
3
4 int main() {
5 char str_a[20];
6
7 strcpy(str_a, "Hello, world!\n");
8 printf(str_a);
9 }
(gdb) break 6
Breakpoint 1 at 0x80483c4: file char_array2.c, line 6.
(gdb) break strcpy
Search WWH ::




Custom Search