me again :P, anyway, I have been working on a C program to allow users to login to a website, very very basic.

My code however is giving me a segmentation fault.

The information is passed via HTML POST to C, which is then stored in a .ssv file as USERNAME PASSWORD

When running it from the site I get premature end of script headers, and when running from bash, I get segmentation fault.

Here is my code:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(void){
    char* s = malloc(100 * sizeof(char));
    char* s2 = malloc(100 * sizeof(char));
    int a=0;

    printf("Content-type: text/html;charset=utf-8\n\n");
    printf("<html>\n");
    printf("<body>\n");
    printf("<h1>Form Feedback</h1>\n");
    int n = atoi(getenv("CONTENT_LENGTH"))+1;
    char theString[n];
    fgets(theString, n, stdin);
   // theString = getenv("QUERY_STRING");
    if(theString == NULL){
        printf("<h2>Error</h2>\n");
        return 0;
    }

    char parseValue[] = "&";
    char* str = strtok(theString, parseValue);
//    str = strtok(NULL, parseValue);
    sscanf(str, "name=%s", s);

    for (a=0; a<strlen(s); a++){
    if(s[a]=='+'){
        printf("<p>Please only use alfanumeric characters</p>");}
    } 

//    str = strtok(NULL, parseValue);
    sscanf(str, "password=%s", s2);


    for (a=0; a<strlen(s2); a++){
        if(s2[a]=='+'){
                printf("<p>Please only use alfanumeric characters</p>");}
    }


    printf("<br><br><h1>REGISTRATION COMPLETE</h1>");

    printf("</body>");
    printf("</html>");


    FILE *file;
    file=fopen("members.ssv", "a+");
    if(file==NULL){return 1;}
    sprintf(str,"%s %s\n",s,s2);
    fwrite(str,1,sizeof(str),file);
    fclose(file);

    return 0;
}

Thank you so much if you can help, I've been stuck for days.

EDIT: I fixed the segmentaton fault, and premature end of script headers. HOWEVER, when I look at my members.ssv file, I get something like

START OF FILE: blank *blank* @R

I have no clue why!

有帮助吗?

解决方案

You have not indicated which part of your code causes the segfault, and maybe you haven't figured that much out, but working back to front I find these things to be suspect:

sprintf ( str , "...", ... ); // 5th line from end. ** edited

At this moment, s is pointing to a small token from strtok. The internals are not going to be clear. You should only sprintf() to something you know the size of. This is most likely the culprit.

It's also possible that strtok has not nul-terminated your strings in the fashion you expected; maybe it won't ever, or maybe that next token you expected did not exist. Have your tested in itself your strtok(),sscanf() methodology? memset()'ing the entirety your s and s2 buffers to '\0' may be recommended.

Also, storing passwords anywhere as strings is dangerous.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top