user2052436
user2052436

Reputation: 4765

std::memset with zero count and invalid pointer

Is it safe to call std::memset(pointer, ch, count) with invalid pointer (e.g., nullptr or junk) when count equals 0?

Upvotes: 3

Views: 211

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29965

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.

Upvotes: 6

Related Questions