首页 > 解决方案 > 使用 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);
}

标签: cpopen

解决方案


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

你的问题可能在这里:

 strcat(chaine,string); 

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

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

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


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

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

因为密码的大小为 32 并且sprintf将写入 33 个字符来放置最后的空字符


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


推荐阅读