16.01.2015 Views

Hacking

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

the English language, knowledge of low-level programming concepts can<br />

assist the comprehension of higher-level ones. When continuing to the next<br />

section, remember that C code must be compiled into machine instructions<br />

before it can do anything.<br />

0x261<br />

Strings<br />

The value "Hello, world!\n" passed to the printf() function in the previous<br />

program is a string—technically, a character array. In C, an array is simply a<br />

list of n elements of a specific data type. A 20-character array is simply 20<br />

adjacent characters located in memory. Arrays are also referred to as buffers.<br />

The char_array.c program is an example of a character array.<br />

char_array.c<br />

#include <br />

int main()<br />

{<br />

char str_a[20];<br />

str_a[0] = 'H';<br />

str_a[1] = 'e';<br />

str_a[2] = 'l';<br />

str_a[3] = 'l';<br />

str_a[4] = 'o';<br />

str_a[5] = ',';<br />

str_a[6] = ' ';<br />

str_a[7] = 'w';<br />

str_a[8] = 'o';<br />

str_a[9] = 'r';<br />

str_a[10] = 'l';<br />

str_a[11] = 'd';<br />

str_a[12] = '!';<br />

str_a[13] = '\n';<br />

str_a[14] = 0;<br />

printf(str_a);<br />

}<br />

The GCC compiler can also be given the -o switch to define the output<br />

file to compile to. This switch is used below to compile the program into an<br />

executable binary called char_array.<br />

reader@hacking:~/booksrc $ gcc -o char_array char_array.c<br />

reader@hacking:~/booksrc $ ./char_array<br />

Hello, world!<br />

reader@hacking:~/booksrc $<br />

In the preceding program, a 20-element character array is defined as<br />

str_a, and each element of the array is written to, one by one. Notice that the<br />

number begins at 0, as opposed to 1. Also notice that the last character is a 0.<br />

(This is also called a null byte.) The character array was defined, so 20 bytes<br />

are allocated for it, but only 12 of these bytes are actually used. The null byte<br />

38 0x200

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!