Free (): invalid next size (fast) error

So, I continue to work with this error: free(): invalid next size(fast)when I run my code. If I delete the free one at the end of the function, I know that I have a memory leak, but I do not understand why I am getting this error.

I assume this is due to the fact that I am allocating memory incorrectly, but I cannot find a 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 this helps the const char*form passed in a line :

method SP request-target SP HTTP-version CRLF

Where SP is the space, and CRLF is the carriage return, line feed.

+4
source share
2 answers

Change this:

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

:

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

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

, , line, , NULL (, , c -life)!;)


, , ( ).:)

+4

:

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

. . . :

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

:

sizeof line: 8
strlen line: 14

strlen + 1 ( ).

+2

Source: https://habr.com/ru/post/1652264/


All Articles