Hacking - The Art of Exploitation, 2nd Edition

(Romina) #1
Programming 19

Functions aren’t commonly used in pseudo-code, since pseudo-code is
mostly used as a way for programmers to sketch out program concepts before
writing compilable code. Since pseudo-code doesn’t actually have to work,
full functions don’t need to be written out—simply jotting down Do some
complex stuff here will suffice. But in a programming language like C, functions
are used heavily. Most of the real usefulness of C comes from collections of
existing functions called libraries.

0x250 Getting Your Hands Dirty


Now that the syntax of C feels more familiar and some fundamental program-
ming concepts have been explained, actually programming in C isn’t that big
of a step. C compilers exist for just about every operating system and processor
architecture out there, but for this book, Linux and an x86 -based processor
will be used exclusively. Linux is a free operating system that everyone has
access to, and x86 -based processors are the most popular consumer-grade
processor on the planet. Since hacking is really about experimenting, it’s
probably best if you have a C compiler to follow along with.
Included with this book is a LiveCD you can use to follow along if your
computer has an x86 processor. Just put the CD in the drive and reboot
your computer. It will boot into a Linux environment without modifying your
existing operating system. From this Linux environment you can follow
along with the book and experiment on your own.
Let’s get right to it. The firstprog.c program is a simple piece of C code
that will print “Hello, world!” 10 times.

firstprog.c


#include <stdio.h>

int main()
{
int i;
for(i=0; i < 10; i++) // Loop 10 times.
{
puts("Hello, world!\n"); // put the string to the output.
}
return 0; // Tell OS the program exited without errors.
}

The main execution of a C program begins in the aptly named main()
function. Any text following two forward slashes (//) is a comment, which is
ignored by the compiler.
The first line may be confusing, but it’s just C syntax that tells the com-
piler to include headers for a standard input/output (I/O) library named
stdio. This header file is added to the program when it is compiled. It is
located at /usr/include/stdio.h, and it defines several constants and func-
tion prototypes for corresponding functions in the standard I/O library.
Since the main() function uses the printf() function from the standard I/O
Free download pdf