Search code examples
cpopen

Segmentation Fault when I use popen()


I have a function to encrypt some string. It's fabulous but ... it's bug :(

I can use the function one time, but the second time, crash.

Thank you ! :)

I working with bash ubuntu (W10), no warning (and error) when i compile my project.

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);
}

Solution

  • Segmentation Fault when I use popen()

    your problem is probably here :

     strcat(chaine,string); 
    

    if the input parameter string more the other fields are too large for chaine and in that case you write out of it with an undefined behavior (it seems a crah in your case)

    Compute the needed length then allocate the string before to fill it.

    Note you can do that in a lazy way with two calls to snprintf, a first to compute the needed size and the second to fill the command. Is a lazy way because here you just concatenate strings, you don't write numbers etc needing a non constant size.


    However is can be also here after the popen :

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

    because password is sized 32 and sprintf will writes 33 character to also place the final null character


    And if miraculously you return from the function you will probably not survive of the use of the result because it is NULL or a pointer to the stack not anymore valid : password is a local variable so strtok returns NULL or the address of password becoming the result of the function