in code below, in "parse" function trying substring string "line". printing "method" variable, "requesttarget" , "httpversion" variables empty reason.
(ps these printf's inside parse function)
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> //prototypes bool parse(const char* line, char* abs_path, char* query); int strindex(char** pos, const char* str); void substr(int start, int end, char* holder, const char* line); int main(void) { const char* line = "get /hello.php?name=alice http/1.1"; char* abs_path = null; char* query = null; if(parse(line, abs_path, query)) { printf("it works!\n"); } } bool parse(const char* line, char* abs_path, char* query) { char* space; int firstspace; int secondspace; char* method = malloc(50 * sizeof(char)); char* requesttarget = malloc(50 * sizeof(char)); char* httpversion = malloc(50 * sizeof(char)); space = strchr(line, ' '); printf("%p\n", space); //checks if strchr returns if(space == null) { return false; } //index in int of character firstspace = strindex(&space, line); printf("%i\n", firstspace); //stores method substr(0, firstspace, method, line); space = strrchr(line, ' '); printf("%p\n", space); //index in int of character secondspace = strindex(&space, line); printf("%i\n", secondspace); //checks if strchr returns if(space == null) { return false; } //firstspace should come before secondspace if(firstspace > secondspace) { return false; } //stores request - target substr(firstspace + 1, secondspace, requesttarget, line); //stores http-version substr(secondspace + 1, strlen(line), httpversion, line); printf("method: %s\n", method); printf("requesttarget: %s\n", requesttarget); printf("httpversion: %s\n", httpversion); return true; } int strindex(char** pos, const char* str) { for(int = 0, n = strlen(str); < n; i++) { if((str + i) == *pos) { return i; } } return -1; } void substr(int start, int end, char* holder, const char* line) { //char* holder = malloc(50 * sizeof(char)); int = start; for(; < end; i++) { holder[i] = line[i]; } holder[i] = '\0'; //return holder; }
void substr(int start, int end, char* holder, const char* line) { //char* holder = malloc(50 * sizeof(char)); int = start, j=0; for(; < end; i++) { holder[j++] = line[i]; } holder[j] = '\0'; //return holder; }
you not storing data in holder 2nd iteration properly. 2nd iteration start = 3 , end = 25. while storing in holder index starts 3, correct line not holder. add 1 more variable start index holder 0.
Comments
Post a Comment