[英]C not allocating memory for new char array
我看不到以下代码如何在字符数组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
crypt()
返回一个指向静态分配缓冲区的指针。 每次对crypt()
调用都会覆盖先前的结果。
http://man7.org/linux/man-pages/man3/crypt.3.html
返回值指向静态数据,其每次调用都会覆盖其内容。
在这种情况下,不需要malloc
调用。 实际上,您最终会遇到无法访问的内存,您现在无法free
内存,因为您用crypt()
的结果覆盖了指针
crypt()
函数具有内部存储器,每个调用都会覆盖以前的结果。
为'ss'然后为'tt'调用crypt()
和printf()
或使用可重入版本
#define _GNU_SOURCE 1
#include <crypt.h>
#include <unistd.h>
#include <pwd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *cd;
cd = malloc(30 * sizeof(*cd));
char *cd2;
cd2 = malloc(30 * sizeof(*cd2));
struct crypt_data *data = calloc(1, sizeof (struct crypt_data));
struct crypt_data *data2 = calloc(1, sizeof (struct crypt_data));
cd2 = crypt_r("yum", "ss", data2);
cd = crypt_r("yum", "tt", data);
printf("hasehd 'yum' with 'ss' salt is %s\n",cd2);
printf("hasehd 'yum' with 'tt' salt is %s\n",cd);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.