Search code examples
carrayspointersmemcmp

Why do the addresses of initial array elements compare equal?


I have been working on a project and I spent the last hour trying to find the bug in my code. After closer inspection, I noticed something rather odd which has been the problem all along.

The addresses of the initial elements of my array are strangely comparing equal with memcmp(). I have separated my code and tried a test code, and I got similar results. Can somebody explain this odd behavior?

#include <stdio.h>
#include <string.h>

int main(void)
{
    char buf[256];

    char *p1 = buf;
    char *p2 = buf + 3;

    if (memcmp(p1, p2, sizeof(char *)) == 0) {
        puts("equal...");
    }

    p1 = buf + 100;
    p2 = p1  + 3; 

    if (memcmp(p1, p2, sizeof(char *)) == 0) {
        puts("equal...");
    }
    return 0;
}

Solution

  • You have undefined behavior.

    Local variables, no matter if simple integers or arrays, are not initialized. Their value is indeterminate. Using them in any way, even reading from them, before initialization leads to undefined behavior.

    Also, you are not comparing two characters, you are comparing 4 or 8 characters at a time, depending on if you're on a 32 or 64 bit system. If you want to compare single characters you should use sizeof(char) (which is specified to always be equal to 1). Neither are you comparing the pointers, you are comparing what they point to.

    If you want to compare two single characters use the compare-equal operator == instead, like e.g. *p1 == *p2 or plainly buf[0] == buf[3].