SillyRab
SillyRab

Reputation: 75

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.

Upvotes: 5

Views: 4307

Answers (2)

Miguel Sosa
Miguel Sosa

Reputation: 72

On the line:

char* copy = malloc(sizeof(line)); //allocate space for a copy of the line parameter

You are allocating memory to hold the size of a pointer. You need to allocate the length of the string instead. See the following:

#include <stdio.h>
#include <string.h>

int main(int argc, const char* argv[]) {
  const char *line = "this is a line";
  printf("sizeof line: %zu\n", sizeof(line));
  printf("strlen line: %zu\n", strlen(line));
  return 0;
}

output:

sizeof line: 8
strlen line: 14

You should allocate on strlen+1 (to account for the null character).

Upvotes: 3

gsamaras
gsamaras

Reputation: 73366

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 -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). :)

Upvotes: 6

Related Questions