I have this parser, I want to use the size of the pointer (that is 8 bytes) in the function strncpy, I was able do it with the "method" part, why does it crash the "path" part ?
It tells me Segmentation fault (core dumped) in the path part, so it does not have the authorization?
Am I missing something ?
int http_parser(char *request) {
char tmp_request[BUFFER_SIZE];
char *method;
char *path;
strncpy(tmp_request, request, sizeof(tmp_request));
char *token = strtok(tmp_request, " ");
if (token == NULL) {
printf("\nInvalid Request Format!");
return 0;
}
//METODO
strncpy(method, token, sizeof(method));
token = strtok(NULL, " ");
//printf("METODO!\n");
if (token == NULL) {
printf("Invalid Request Method!\n");
return 0;
} else {
printf("Metodo : %s\n",method);
}
//path
strncpy(path, token, sizeof(path));
token = strtok(NULL, " ");
printf("PATH\n");
if (token == NULL) {
printf("Invalid Request Path\n");
return 0;
} else {
printf("Path : %s\n",path);
}
}
I tried using sizeof(8) and it works, but I want to know why it doesn't work when I do it this way.
methodis uninitialized (and does not point to allocated memory) when it is used instrncpy(method, token, sizeof(method));. Alsosizeof(method)is the size of the pointer, not the data it's supposed to be pointing to.strncpybystrdupfor instance (but warning, that dynamically allocate memory, so you will have tofreethem later). But if the goal is just to print the tokens, just print token each timestrncpy()doesn't null-terminate the copied string if it is bigger than the array. GCC with enough warnings enabled will point that out.