使用popen()时的分段错误

问题描述 投票:-3回答:1

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

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

谢谢 ! :)

我使用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);
}
c popen
1个回答
1
投票

使用popen()时的分段错误

你的问题可能在这里:

 strcat(chaine,string); 

如果输入参数字符串越多,其他字段对于链接来说太大,并且在这种情况下你用不确定的行为写出它(在你的情况下看起来很糟糕)

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

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


然而,在popen之后也可以在这里:

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

因为密码大小为32而sprintf会写入33个字符也会放置最终的空字符


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

© www.soinside.com 2019 - 2024. All rights reserved.