Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Secure way to realloc

Tags:

c

I'm writing a C library which needs to often move around various sensitive data. I want to have benefits of realloc (extending allocated block instead copying when memory is available) while having some way to erase content of old block if copying is necessary.

Is there some lightweight implementation of malloc/realloc/free which could be used for mingw-gcc or some other trick to it, or I must overallocate and just allocate-and-copy without relying on realloc?

like image 365
William Chapa Avatar asked Jun 19 '17 15:06

William Chapa


People also ask

Is realloc safe to use?

It's perfectly safe to use realloc . It is the way to reallocate memory in a C program. However you should always check the return value for an error condition.

Does realloc destroy data?

No, the data will be copied for you into the new block that the returned p points at, before the old block is freed. This all happens before realloc returns, so the new p points to your data still.

When should I use realloc?

In the C Programming Language, the realloc function is used to resize a block of memory that was previously allocated. The realloc function allocates a block of memory (which be can make it larger or smaller in size than the original) and copies the contents of the old block to the new block of memory, if necessary.

Should you free after realloc?

Once you call realloc() , you do not have to free() the memory addressed by pointer passed to realloc() - you have to free() the memory addressed by the pointer realloc() returns. (Unless realloc() returns NULL , in which case the original block of memory - passed to realloc() - has to be free() 'd.) Save this answer.


1 Answers

On Linux, mmap the block, mlock it, and then do mremap instead of using realloc.

Protecting against hidden copies isn't enough. You also need to make sure the memory never ever gets swapped to disk before you get a chance to zero it.

like image 64
PSkocik Avatar answered Oct 19 '22 08:10

PSkocik