21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

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

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

If you prefer to give programmers the chance to handle the problem, you could<br />

throw an exception. In such a case, we recommend using the standard errno values<br />

as exception codes and using positive integers above 256 for application-specific<br />

exceptions.<br />

#include <br />

#include <br />

#include <br />

#define EXCEPTION_OUT_OF_MEMORY (ENOMEM)<br />

void *my_malloc(size_t sz) {<br />

void *res = malloc(sz);<br />

/* We pass the amount of memory requested as extra data. */<br />

if (!res) RAISE(EXCEPTION_OUT_OF_MEMORY, (void *)sz);<br />

return res;<br />

}<br />

See Also<br />

XXL exception handling library for C: http://www.zork.org/xxl/<br />

13.2 Erasing Data from Memory Securely<br />

<strong>Problem</strong><br />

You want to minimize the exposure of data such as passwords and cryptographic<br />

keys to local attacks.<br />

Solution<br />

You can only guarantee that memory is erased if you declare it to be volatile at the<br />

point where you write over it. In addition, you must not use an operation such as<br />

realloc( ) that may silently move sensitive data. In any event, you might also need<br />

to worry about data being swapped to disk; see Recipe 13.3.<br />

Discussion<br />

Securely erasing data from memory is a lot easier in C and C++ than it is in languages<br />

where all memory is managed behind the programmer’s back. There are still<br />

some nonobvious pitfalls, however.<br />

One pitfall, particularly in C++, is that some API functions may silently move data<br />

behind the programmer’s back, leaving behind a copy of the data in a different part<br />

of memory. The most prominent example in the C realm is realloc( ), which will<br />

sometimes move a piece of memory, updating the programmer’s pointer. Yet the old<br />

704 | Chapter 13: Other Topics<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!