Search code examples
c++cundefined-behaviorc-stringsstrcmp

why the return values of function strcmp() in for(){} are different and increasing?


in this example

for(int i = 0; i < 4; i++) {
    char c = 's';
    printf("%d\n", strcmp(&c, "s"));
}

output : 0, 1, 2, 3

why the return values of function strcmp() in for(){} are different and increasing?


Solution

  • The code snippet has undefined behavior because the function strcmp is designed to compare strings. But the pointer expression &c in this statement

    printf("%d\n", strcmp(&c, "s"));
    

    does not point to a string. It points to a single object of the type char after which the memory can contain anything.

    So it seems the memory after the object c is somehow being overwritten in each iteration of the for loop after the statement above.

    Instead you should write

    const char *c = "s";
    
    printf("%d\n", strcmp(c, "s"));