Is it safe to call std::memset(pointer, ch, count)
with invalid pointer (e.g., nullptr
or junk) when count
equals 0?
No, that causes undefined behavior. For example:
void* p = get_address(); // may return null
size_t sz = get_size(); // zero if previous returned null
memset(p, 0, sz); // Compiler may assume that p is not null
if (p) { // this null-check can be omitted since we "know" p is not null
foo(p);
}
And indeed, if you look at the code generated by GCC:
main:
push rbx
call get_address()
mov rbx, rax
call get_size()
mov rdi, rbx
xor esi, esi
mov rdx, rax
call memset
mov rdi, rbx
call foo(void*) ; <-- unconditional call
xor eax, eax
pop rbx
ret
You can see that the "if" branch is omitted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With