【问题标题】:Segmentation Fault when I use popen()使用 popen() 时出现分段错误
【发布时间】:2019-08-24 00:16:54
【问题描述】:

我有一个加密一些字符串的功能。 这太棒了,但是......这是错误:(

我可以使用该功能一次,但第二次,崩溃。

谢谢! :)

我使用 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的返回值?
  • sprintf(password,"%32s",path); 应该说31,因为数组是char password[32];。奇怪的是你替换了password = (char *)malloc(33*sizeof(char));。我想你应该有char password[33];
  • 不要对预定义的字符串使用任意长度的缓冲区。 char* chaine = "echo"。这将阻止您考虑连接到它们,因为您不应该这样做。而是使用专门用于连接的缓冲区。这段代码似乎充斥着关于各种字符串长度的疯狂假设,因此您可能在这里遇到大量缓冲区溢出问题。
  • 除此之外,MD5 不适合散列密码。它太弱了,使用现代工具几乎可以立即破解较短的密码。这些天的绝对基线是一个特定于密码的哈希,其难度可变,例如Bcrypt
  • 我知道 fo md5 但谢谢 :)

标签: c popen


【解决方案1】:

使用 popen() 时出现分段错误

你的问题可能在这里:

 strcat(chaine,string); 

如果输入参数 string 更多,其他字段对于 chaine 来说太大了,在这种情况下,您会以未定义的行为写出它(这似乎是一个崩溃你的情况)

计算所需的长度,然后分配之前的字符串来填充它。

请注意,您可以通过两次调用 snprintf 以一种懒惰的方式执行此操作,第一次用于计算所需的大小,第二次用于填充命令。是一种懒惰的方式,因为在这里你只是连接字符串,你不写需要非恒定大小的数字等。


但是也可以在 popen 之后出现在这里:

sprintf(password,"%32s",path);

因为 password 的大小为 32,而 sprintf 将写入 33 个字符来放置最后的空字符


如果你奇迹般地从函数返回,你可能无法使用结果,因为它是 NULL 或 指向堆栈的指针不再有效密码 是一个局部变量,所以 strtok 返回 NULL 或 password 的地址成为函数的结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-06
    • 2017-08-26
    • 2018-06-18
    • 2019-05-10
    • 2018-02-15
    • 2016-01-15
    • 2011-01-14
    • 2013-01-03
    相关资源
    最近更新 更多