I'm currently working on PSET6 and had a question for the parsing section. I decided to use strtok() and as a result, will need to malloc memory when creating new char*. How do i know how much memory to assign/ what would be a safe amount? I know I can set an arbitrarily large number, but how do i dynamically allocate it? Or is that needed? Below is the beginning part of my code.

Thanks a bunch!

char* copyLine = malloc(sizeof(char*) + 100);

char* method = malloc(sizeof(char*) + 100);
method = strtok(copyLine, " ");
char* request_target = malloc(sizeof(char*) + 100);
request_target=  strtok(NULL, " ");
char* HTTP_version = malloc(sizeof(char*) + 100);
HTTP_version = strtok(NULL, " ");


So my question is specifically, what do i put inside malloc()/ how do i know how big to assign a char*.


1 Answer 1


The correct way to go about allocating memory dynamically would be:

char* copyLine = malloc((sizeof(char) * strlen(line)) + 1); // +1 for '\0'
strcpy(copyLine, line);

Use strlen() so you know exactly how many bytes you need to allocate for what you are copying. Multiply that by the size of a char then add 1 and bingo you got yerself dynamically aloccamated memory.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .