Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free() : invalid next size (fast) error

So I keep running to this error: free(): invalid next size(fast) when I run my code. If I remove the free at the end of the function I know I am leaking memory but I don't understand why I am getting this error.

I assume it has something to do with me allocating memory incorrectly but I can't seem to find the fix, here is my code:

bool parse(const char* line) //NOT WORKING JUST QUITE 
{
    char* copy = malloc(sizeof(line)); //allocate space for a copy of the line parameter
    strcpy(copy, line); //copy the line parameter

    char* method = strtok(copy, " "); //pointer to the method 
    char* reqLine = strtok(NULL, " "); //pointer to the requestline
    char* version = strtok(NULL, "\r\n"); //pointer to the HTTP-Version

    if (strcmp(method,"GET") != 0) //if the method is not GET
    {
        printf("%s\n", method);
        printf("ERROR 405\n");
        return false;
    }
    if (strncmp(reqLine, "/", 1) != 0)//if the request line does not begin with a / character
    {
        printf("%c\n", reqLine[0]);
        printf("%s\n", reqLine);
        printf("ERROR 501\n");
        return false; 
    }
    if (strchr(reqLine, 34) != NULL) //if the request line contains a " character
    {
        printf("%s\n", reqLine);
        printf("ERROR 400\n");
        return false;
    }
    if (strcmp(version, "HTTP/1.1") != 0)
    {
        printf("%s", version);
        printf("ERROR 505\n");
        return false;
    }

//free(copy); 
return true;
}

If it helps the passed in const char* line is of the form:

method SP request-target SP HTTP-version CRLF

Where SP is a space and CRLF is carridge return, line feed.

like image 237
SillyRab Avatar asked Mar 11 '23 08:03

SillyRab


1 Answers

Change this:

char* copy = malloc(sizeof(line));

to this:

char* copy = malloc(strlen(line) + 1);

The first allocates space for the size of line, which is a POINTER!

While the second, allocates space equal to the length of the string that line points to, plus one, for the NULL terminator (please don't forget that and you will live a happier c-life)! ;)


BTW, I believe that it's more common to write the comments of your code above the line of code (rather than next to it). :)

like image 137
gsamaras Avatar answered Mar 29 '23 01:03

gsamaras