Graphics Programs Reference
In-Depth Information
reader@hacking:~/booksrc $ ./a.out 'Hello, world!' 3
Repeating 3 times..
0 - Hello, world!
1 - Hello, world!
2 - Hello, world!
reader@hacking:~/booksrc $
In the preceding code, an if statement makes sure that three arguments
are used before these strings are accessed. If the program tries to access mem-
ory that doesn't exist or that the program doesn't have permission to read,
the program will crash. In C it's important to check for these types of condi-
tions and handle them in program logic. If the error-checking if statement is
commented out, this memory violation can be explored. The convert2.c
program should make this more clear.
convert2.c
#include <stdio.h>
void usage(char *program_name) {
printf("Usage: %s <message> <# of times to repeat>\n", program_name);
exit(1);
}
int main(int argc, char *argv[]) {
int i, count;
// if(argc < 3) // If fewer than 3 arguments are used,
// usage(argv[0]); // display usage message and exit.
count = atoi(argv[2]); // Convert the 2nd arg into an integer.
printf("Repeating %d times..\n", count);
for(i=0; i < count; i++)
printf("%3d - %s\n", i, argv[1]); // Print the 1st arg.
}
The results of compiling and executing convert2.c are as follows.
reader@hacking:~/booksrc $ gcc convert2.c
reader@hacking:~/booksrc $ ./a.out test
Segmentation fault (core dumped)
reader@hacking:~/booksrc $
When the program isn't given enough command-line arguments, it still
tries to access elements of the argument array, even though they don't exist.
This results in the program crashing due to a segmentation fault.
Memory is split into segments (which will be discussed later), and some
memory addresses aren't within the boundaries of the memory segments the
program is given access to. When the program attempts to access an address
that is out of bounds, it will crash and die in what's called a segmentation fault .
This effect can be explored further with GDB.
Search WWH ::




Custom Search