### 8.3 Buffer overflow protection ¶

The GCC macro definition of `-D_FORTIFY_SOURCE` provides a lightweight buffer overflow protection to some memory and string functions provided by the GLIBC. This feature uses macro substitution of such vulnerable functions to prevent an insecure buffer overflow code to be executed. The compiler optimization option needs to be `-O1` or higher to enable `-D_FORTIFY_SOURCE`.25

The insecure program `bof.c` shown in the previous section can be compiled with the option `-D_FORTIFY_SOURCE=2 -O2`.

    $ gcc -Wall -D_FORTIFY_SOURCE=2 -O2 bof.c -o bof-fort
    $ ./bof-fort '123456789' || echo error
    >>> Before the possible buffer over flow >>>
    *** buffer overflow detected ***: ./bof-fort terminated
    ... [snipped]
    Aborted
    Error

The output shows that the `bof.c` program compiled with the option `-D_FORTIFY_SOURCE=2 -O2` creates an executable `bof-fort` which stops before executing an insecure buffer overflow code.

This `-D_FORTIFY_SOURCE` option is a quick fix for older programs written with fixed length buffers. But if you are writing a software program from scratch, please consider to use the secure libraries such as the `GLib` library26 instead of the standard `Libc` library.

#### Footnotes

##### (25)

http://www.redhat.com/archives/fedora-tools-list/2004-September/msg00002.html

##### (26)

http://en.wikipedia.org/wiki/GLib