Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can placement new survive optimization, unlike memset?

So I'm really intrigued about whether or not it can survive aggressive optimization tactics employed by GCC and clang.

Considering the following example:

void* clean(void* pointer, std::size_t size) noexcept
{
    return new(pointer) char[size]{};
}

void doStuff()
{
    //...
    clean(pointer, size);
    //...
}

Can I trust it with the task of cleaning sensitive data?

like image 707
bit2shift Avatar asked Mar 10 '16 17:03

bit2shift


1 Answers

I do not think optimization can play any tricks on you here. Standard mandates value initialization in this case: new(pointer) char[size]{}, so after this call memory pointed to by pointer would be filled with 0.

May be compiler can optimize it if you never access the new pointer or override it before accessin (based on observability). If you want to avoid this slight possibility, you'd need to define your pointer as a pointer to volatile.

like image 126
SergeyA Avatar answered Oct 02 '22 14:10

SergeyA