26.07.2018 Views

hacking-the-art-of-exploitation

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

This same technique can be used in a multiuser note-taking program.<br />

The next program will be a modification <strong>of</strong> <strong>the</strong> simplenote program; it will<br />

also record <strong>the</strong> user ID <strong>of</strong> each note’s original author. In addition, a new<br />

syntax for #include will be introduced.<br />

The ec_malloc() and fatal() functions have been useful in many <strong>of</strong> our<br />

programs. Ra<strong>the</strong>r than copy and paste <strong>the</strong>se functions into each program,<br />

<strong>the</strong>y can be put in a separate include file.<br />

<strong>hacking</strong>.h<br />

// A function to display an error message and <strong>the</strong>n exit<br />

void fatal(char *message) {<br />

char error_message[100];<br />

}<br />

strcpy(error_message, "[!!] Fatal Error ");<br />

strncat(error_message, message, 83);<br />

perror(error_message);<br />

exit(-1);<br />

// An error-checked malloc() wrapper function<br />

void *ec_malloc(unsigned int size) {<br />

void *ptr;<br />

ptr = malloc(size);<br />

if(ptr == NULL)<br />

fatal("in ec_malloc() on memory allocation");<br />

return ptr;<br />

}<br />

In this new program, <strong>hacking</strong>.h, <strong>the</strong> functions can just be included. In C,<br />

when <strong>the</strong> filename for a #include is surrounded by < and >, <strong>the</strong> compiler looks<br />

for this file in standard include paths, such as /usr/include/. If <strong>the</strong> filename<br />

is surrounded by quotes, <strong>the</strong> compiler looks in <strong>the</strong> current directory. Therefore,<br />

if <strong>hacking</strong>.h is in <strong>the</strong> same directory as a program, it can be included<br />

with that program by typing #include "<strong>hacking</strong>.h".<br />

The changed lines for <strong>the</strong> new notetaker program (notetaker.c) are<br />

displayed in bold.<br />

notetaker.c<br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

#include "<strong>hacking</strong>.h"<br />

void usage(char *prog_name, char *filename) {<br />

printf("Usage: %s \n", prog_name, filename);<br />

exit(0);<br />

Programming 91

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

Saved successfully!

Ooh no, something went wrong!