c - 使用 popen() 时出现分段错误
问题描述
我有一个加密一些字符串的功能。这太棒了,但是......这是错误:(
我可以使用该功能一次,但第二次,崩溃。
谢谢 !:)
我使用 bash ubuntu(W10),编译我的项目时没有警告(和错误)。
char * encryptPassword(char * string){
printf("DEBUT\n");
FILE *fp=NULL;
char path[1035];
char password[32];
//char * password = NULL; //for the encrypt password
printf("MALLOC\n");
//password = (char *)malloc(33*sizeof(char));
char * result = NULL;
char chaine[128] = "echo ";
char end_chaine[128] = " | openssl md5 | cut -d ' ' -f2";
//Create the command
printf("STRCAT\n");
strcat(chaine,string);
strcat(chaine,end_chaine);
//Execute
printf("POPEN %s\n",chaine);
fp = popen(chaine, "r");
//Reclaim the encrypted password
printf("GETS\n");
fgets(path, sizeof(path)-1, fp);
pclose(fp);
//To remove the character '\n'
printf("SPRINTF\n");
sprintf(password,"%32s",path);
result = strtok(password,"\n");
printf("%s\n",result);
//OK IT'S FINISH !
return (result);
}
解决方案
使用 popen() 时出现分段错误
你的问题可能在这里:
strcat(chaine,string);
如果输入参数字符串更多,则其他字段对于chaine来说太大了,在这种情况下,您会以未定义的行为写出它(在您的情况下似乎是错误的)
计算所需的长度,然后在填充之前分配字符串。
请注意,您可以通过两次调用snprintf以一种懒惰的方式执行此操作,第一个用于计算所需的大小,第二个用于填充命令。是一种懒惰的方式,因为在这里你只是连接字符串,你不写需要非恒定大小的数字等。
但是在popen之后也可以在这里:
sprintf(password,"%32s",path);
因为密码的大小为 32 并且sprintf将写入 33 个字符来放置最后的空字符
如果你奇迹般地从函数返回,你可能无法使用结果,因为它是 NULL 或指向堆栈的指针不再有效:密码是一个局部变量,所以strtok返回 NULL 或密码的地址成为结果功能的
推荐阅读
- python - 电话号码的 Python 正则表达式表现得很奇怪
- jupyter-notebook - 我如何使用 BERT 进行机器翻译?
- python - 使用 Beautiful Soup 下载图像
- python - 构造具有已知三角形面的凸包对象
- javascript - chart.scrollablePlotArea 意外行为
- vue.js - vue - 与其他锚多次使用相同的网址
- arduino - 希望两个限制之间的数字具有相等的时间间隔
- excel - 自定义 SUMPRODUCT()
- python - Django:打印查询集时出错
- python - 如何像 FFMPEG 一样在 Python 中从音频文件创建频谱图?