0

I am having understanding a weird behavior of strcmp function, which will be illustrated by the following code:

#include <iostream> 
#include <cstring>

using namespace std;

int main()
{
    char *p = "no";

    cout << p << endl;                      //Output: no
    cout << &p << endl;                     //Output: 0x28ac64
    cout << strlen(p) << endl;              //Output: 2
    cout << strcmp(p, "no") << endl;        //Output: 0

    cin >> p;                               //Input: bo

    cout << p << endl;                      //Output: bo
    cout << &p << endl;                     //Output: 0x28ac64
    cout << strlen(p) << endl;              //Output: 2

    cout << strcmp(p, "no") << endl;        //Output: 0
    return 0;
}

What I fail to understand is why the output of line 15 is 0. 0 means the two strings are equal, which is clearly not the case. What am I missing here?

P.S. I do apologize for the escape characters in the headers, but I could not get iostream to display if I removed it. Though I am posting this, I will figure out how to get it right for next time. :)

joce
  • 9,624
  • 19
  • 56
  • 74

3 Answers3

6

The problem is that p points to a string literal, therefore your attempt to modify the string literal with cin >> p; leads directly to undefined behavior.

What's most likely happening is that the compiler is treating the string literal as constant (since you're not supposed to modify it) and therefore, (at compile time) determining what the result from strcmp should be, and producing that. The fact that you're modifying it at run-time is ignored, because you're not supposed to do that anyway.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
3

Unfortunately for compatibility many compilers support this:

char *p = "no";

Which should fail to compile and correct one is:

const char *p = "no";

If you fix that (and you should get at least warning), you would see what is the issue with following compile errors.

Slava
  • 43,454
  • 1
  • 47
  • 90
1

p is pointing to the first element of an array of const char. Attempting to modify these values (as you do in cin >> p) invokes undefined behaviour.

Mankarse
  • 39,818
  • 11
  • 97
  • 141