Deeven Deeven - 5 months ago 18
C Question

Trying to get the substring but the program is returning empty string

In the code below, in "parse" function I am trying to get substring from the string "line". I am successfully printing the "method" variable, but "requesttarget" and "httpversion" variables are empty for some reason.

(ps all these printf's are also inside my 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 the character
firstspace = strindex(&space, line);

printf("%i\n", firstspace);

//stores the method
substr(0, firstspace, method, line);

space = strrchr(line, ' ');

printf("%p\n", space);

//index in INT of the 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 i = 0, n = strlen(str); i < 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 i = start;
for(; i < end; i++)
{
holder[i] = line[i];
}
holder[i] = '\0';
//return holder;
}

Answer
 void substr(int start, int end, char* holder, const char* line)
    {
        //char* holder = malloc(50 * sizeof(char));
        int i = start, j=0;
        for(; i < end; i++)
        {
            holder[j++] = line[i];
        }
        holder[j] = '\0';
        //return holder;
    }

you were not storing data in holder from 2nd iteration properly. from 2nd iteration start = 3 and end = 25. While storing in holder your index starts from 3, which is correct for line but not for holder. Add one more variable to start the index for holder from 0.