I am trying to fill the gaps in my self-education in computer science and taking the CS50 course on Edx. I am completely new to C. In one of the problems sets, I have to compare strings encrypted with crypt function.
In the following example, I cannot understand why strcmp
returns 0 (i.e. 'claims' that the strings are equal:
#include <crypt.h>
#include <stdio.h>
#include <string.h>
#define _XOPEN_SOURCE
int main(void)
{
char string1[4] = "foo\0";
char string2[4] = "bar\0";
printf("crypt1: %s\n",crypt(string1, "50\0"));
printf("crypt2: %s\n",crypt(string2, "50\0"));
if (strcmp(crypt(string1, "50\0"),crypt(string2, "50\0")) == 0)
{
printf("crypt1: %s\n",crypt(string1, "50\0"));
printf("crypt2: %s\n",crypt(string2, "50\0"));
return 0;
}
}
When I run the program, the output value is:
crypt1: 50GbL/FUeE/J6
crypt2: 50hmnpE.bRNiU
crypt1: 50GbL/FUeE/J6
crypt2: 50hmnpE.bRNiU
How is it possible, that the code inside if
condition is even executed?
Apparently, crypt()
uses the same buffer for the encrypted string on each call:
char string1[] = "foo";
char string2[] = "bar";
char *crypt1 = crypt(string1, "50");
printf("crypt1: %s\n", crypt1); // crypt1: 50GbL/FUeE/J6
char *crypt2 = crypt(string2, "50");
printf("crypt1: %s\n", crypt1); // crypt1: 50hmnpE.bRNiU
printf("crypt2: %s\n", crypt2); // crypt2: 50hmnpE.bRNiU
In order to keep (and compare) both results, you have to strdup()
them or copy them to a separate array.