简体   繁体   中英

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?

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 .

I am not sure whether this is an answer to your question or just a side note but you can disable optimization on that specific function using optimize() compiler directive

void* __attribute__((optimize("O0"))) clean(void* pointer, std::size_t size) {
    // unmodifiable compiler code
}

This will ensure your clean() function will not be optimized away

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM