Search code examples
cstringstrcmp

strcmp returns 1 when 2 strings are equal, Why?


I have the following code. I took it from http://www.gnu.org/software/libc/manual/html_node/crypt.html

#define _XOPEN_SOURCE
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <crypt.h>

int
main(void)
{
  /* Hashed form of "GNU libc manual". */
  const char *const pass = "$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/";

  char *result;
  int ok;

  printf("%s\n",pass);

  /* Read in the user’s password and encrypt it,                                                                                                    
     passing the expected password in as the salt. */
  result = crypt(getpass("Password:"), pass);

  printf("%s\n",result); /*I added this printf*/
  /* Test the result. */
  ok = strcmp (result, pass) == 0;
  printf("valor de la comparacion: %i\n",ok);/*I added it*/
  puts(ok ? "Access granted." : "Access denied.");
  return ok ? 0 : 1;
}

When I type GNU libc manual the output is "Acces granted". but the value returned by strcmp is 1 and this value means that result and pass are not equal. However the output is :

$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/
Password:
$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/
valor de la comparacion: 1
Access granted.

I am very confused about behavior of strcmp.


Solution

  • You are printing the value of ok.

    On this line:

    ok = strcmp (result, pass) == 0;
    

    it compares the return value of strcmp to 0. They are equal, so the comparison is true. That sets ok to 1. Setting an integer to the result of a boolean comparison gives 1 for true, and 0 for false.