Search code examples
cstringcomparisonstring-comparisonstrcmp

strcmp in C returns 1 instead of 0


I wrote the following code in C.

#include <stdio.h>
#include <string.h>
int main(void) {
    char str1[4] = "abcd";
    char str2[4] = "abcd";
    printf("%d\n",strcmp(str1,str2));

    return 0;
}

I expected the return value to be 0 (as I am taught that strcmp function returns 0 for equal strings). But it prints 1!

Success  time: 0 memory: 2248 signal:0
1

Is it a bug? Or am I missing out on something?


Solution

  • Because your arrays are not long enough. Your are not taking into account the zero terminator of your strings. You need 5 chars for your string, four for the string itself plus one for the zero terminator.

    Write:

    char str1[5] = "abcd";
    char str2[5] = "abcd";
    

    BTW I wonder why your compiler does not issue a warning or does it ?