Home > Net >  std::memset with zero count and invalid pointer
std::memset with zero count and invalid pointer

Time:11-10

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

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related