Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It is scary that gcc or glibc manage to break memcmp or memmove on a regular basis.

I begin to understand the people who write their own libc for security reasons.



I can't see that working out the way they expect.


Well, on one hand, writing correct albeit slow memcmp() is easy, on the other hand, it has some gotchas...

    int my_memcmp(const void * ptr1, const void * ptr2, size_t num) {
        const unsigned char * p1 = ptr1;
        const unsigned char * p2 = ptr2;
        for (size_t i = 0; i < num; i++) {
            if p1[i] < p2[i] {
                return -1;
            }
            if p1[i] > p2[i] {
                return 1;
            }
        }
        return 0;
    }
For example, technically speaking, unsigned char can be as wide as an int, so "p1[i] - p2[i]" may actually evaluate to unsigned int which is not what you want.


Nitpick: those if statements need parentheses.

> unsigned char can be as wide as an int, so "p1[i] - p2[i]" may actually evaluate to unsigned int which is not what you want

Would this matter?


I don't think it would; `<` and `>` aren't syntactic sugar in C.


> unsigned char can be as wide as an int

No, it is not true for almost all non-embedded systems. And char cannot be as wide as int, it is the opposite true, int can be as wide as char.


int is guaranteed to be at least as wide as char.


This exactly what I was saying, just made a wrong choice of words.


"Int can be as wide as char" is exactly the same as "char can be as wide as int".


I meant "int can be as narrow as char".




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: