【发布时间】:2019-11-12 09:38:49
【问题描述】:
我看不出下面的代码是如何工作的。 char 数组 cd2 被覆盖。我试图只为两个字符串分配空间,然后用crypt 函数的结果填充它们。我不确定crypt 在这里扮演的角色有多大,或者这是否会影响其他字符串操作功能。但下面的输出不应该相同,它们应该有不同的值。但它们都是“ttxtRM6GAOLtI”,我试图让一个输出以“ss”开头。
#include <crypt.h>
#include <unistd.h>
#include <pwd.h>
#include <string.h>
#include <stdio.h>
int main(int argc, string argv[])
{
char *cd;
cd = malloc(30 * sizeof(*cd));
char *cd2;
cd2 = malloc(30 * sizeof(*cd2));
cd2 = crypt("yum", "ss");
cd = crypt("yum", "tt");
printf("hasehd 'yum' with 'tt' salt is %s\n",cd);
printf("hasehd 'yum' with 'ss' salt is %s\n",cd2);
}
输出 -
hasehd 'yum' with 'tt' salt is ttxtRM6GAOLtI
hasehd 'yum' with 'ss' salt is ttxtRM6GAOLtI
更新:我将其更改为不使用 malloc,但我认为我必须通过 char 数组的声明来分配内存。由于crypt 覆盖了一个静态缓冲区,因此我需要在它被覆盖之前将结果提供给其他地方。
#include <crypt.h>
#include <unistd.h>
#include <pwd.h>
#include <string.h>
#include <stdio.h>
int main(int argc, string argv[])
{
char ch1[30];
char ch2[30];
char *cd;
char *cd2;
cd = &ch1[0];
cd2 = &ch2[0];
snprintf(cd2, 12, "%s\n", crypt("yum", "ss"));
snprintf(cd, 12, "%s\n", crypt("yum", "tt"));
printf("hasehd 'yum' with 'tt' salt is %s\n",cd);
printf("hasehd 'yum' with 'ss' salt is %s\n",cd2);
}
输出 -
hasehd 'yum' with 'tt' salt is ttxtRM6GAOL
hasehd 'yum' with 'ss' salt is ssqDHVWOCwe
更新:我按照建议使用了strcpy,并使用了 malloc 为数组分配空间。 strcpy 似乎更干净一些,因为我不需要提供长度。
#include <crypt.h>
#include <unistd.h>
#include <pwd.h>
#include <string.h>
#include <stdio.h>
int main(int argc, string argv[])
{
int PWORD_LENGTH = 30;
char *cd;
char *cd2;
cd = malloc(sizeof(char) * (PWORD_LENGTH + 1));
cd2 = malloc(sizeof(char) * (PWORD_LENGTH + 1));
strcpy(cd2, crypt("yum", "ss"));
strcpy(cd, crypt("yum", "tt"));
printf("hasehd 'yum' with 'tt' salt is %s\n",cd);
printf("hasehd 'yum' with 'ss' salt is %s\n",cd2);
}
输出 -
hasehd 'yum' with 'tt' salt is ttxtRM6GAOL
hasehd 'yum' with 'ss' salt is ssqDHVWOCwe
【问题讨论】:
-
cd2 = crypt("yum", "ss");-->strcpy(cd2, crypt("yum", "ss"));也对cd做同样的事情。 -
内存分配没有用,因为你立即用
crypt()返回的值覆盖了指针。 -
我不知道
crypt函数,但由于您分配给cd/cd2它必须返回一个指针,这意味着您的malloc是错误的 - 我猜是不必要的。除非你打错了crypt