1. 5

  2. 1

    Tangentially related, but I’ve been bitten by another case of undefined behavior in production code with mem* functions.

    consider this code:

    extern void* get_ptr(size_t* out_n);
    extern void abort();
    int main() {
        size_t n_a, n_b;
        void* a = get_ptr(&n_a);
        void* b = get_ptr(&n_b);
        memcpy(a, b, n_b);
        if (!a) abort();

    abort will never be called because memcpy implies input arguments are non-NULL (godbolt: https://godbolt.org/z/e34ETT). We had some code like memcpy(a, b, n) in which a would be NULL sometimes when n was zero.

    The same is true for many other mem* functions, including memcmp