1

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
NEMOZ
  • 13
  • 4
  • 4
    `strcmp()` takes null-terminated strings. A single `char` is not a null-terminated string. Your program has undefined behavior. – underscore_d Apr 14 '21 at 10:29
  • Welcome to SO. Your code is invalid. `strcmp` expects a pointer to a string as first parameter. You only provide a single character where no proper string termination is present. – Gerhardh Apr 14 '21 at 10:29
  • 1
    `char c` isn't a string, so even though you can get a `char *` by taking its address, that **isn't a string** and doing the comparison results in undefined behaviour. – Karl Knechtel Apr 14 '21 at 10:29
  • 1
    Keeping in mind that anything could happen when you invoke undefined behaviour, a likely reason is that surrounding bytes on the stack are affected by your loop and are interpreted as part of the string. If e.g. your counter is taken as part of the string, it will be incremented and the result will change – Gerhardh Apr 14 '21 at 10:31
  • Write *invalid code*, win **undefined behavior**! – Eljay Apr 14 '21 at 11:22
  • This doesn't address the question, but keep in mind that `strcmp` does not return any particular value for strings that are not equal. The only meaningful things to check for are a return value of 0 for equality, a negative return value if the first string comes before the second, and a positive return value if the first string comes after the second. – Pete Becker Apr 14 '21 at 14:02

1 Answers1

0

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"));
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    @Mb0t_QAQ it makes no sense to analyze it. Now answer me why now it is not increasing: https://godbolt.org/z/Y9z84afhb – 0___________ Apr 14 '21 at 10:50