Felix Rosén Felix Rosén - 3 months ago 8
C Question

How come I can print out each character separately but not as a whole?

This is one part of a server implementation where I'm going through the request line header and giving output accordingly. This might be a basic question. How come I can print out each character separately but not the string as whole?

Has this something to do with mismanagement of memory?

This is part of pset6 in CS50.

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(int argc, char * argv[])
{
char* line = "GET /cat.html HTTP/1.1";

char* method = strstr(line, "GET");
if (strcmp(method, line) != 0)
{
printf("405 Method Not Allowed");
}

printf("%s\n", line);

char* requestTarget = malloc(10);
char* ch = strchr(line,'/');
if (ch != NULL)
{
int i = 0;
for (i = (ch-line); i < strlen(line)-9; i++)
{
requestTarget[i] = line[i];
printf("%c", requestTarget[i]);
}
requestTarget[i] = '\0';
}

else
printf(" 501 Not Implemented");

printf("requestTarget: %s\n", requestTarget);

free(requestTarget);
return 0;
}


A side note, I know it's bad pratice to hard code in
-9
in my for lop
strlen(line)-9
. But I couldn't figure out how to just read the characters in the requested target
cat.html
. And I know that the header is specified by
method SP request-target SP HTTP-version CRLF
(is CRLF aka
\r\n
two characters?) So
-9
works (I think) but maybe not the best.

EDIT: I edited my loop so that I add an null terminator at the end. This was originally meant to be in, but since I have edited my code so much now it was mistakenly taken out. It still does not work though.

Answer

Your code has undefined behavior, because it writes past the space that you allocated.

You do this copy

requestTarget[i] = line[i];

when i points to some location in the middle of the line[], but requestTarget requires a smaller index. You need to "translate" the index, or create a separate one for the destination:

int j = 0;
for (int i = (ch-line); i < strlen(line)-9; i++, j++)
{
    requestTarget[j] = line[i];
    printf("%c", requestTarget[j]);
}
requestTarget[j] = '\0';

Note: you need to make sure that requestTarget has enough space for the characters that you wish to store in it, including the null terminator.

Comments