这是服务器实现的一部分,我将在其中遍历请求行 header 并相应地给出输出。这可能是一个基本问题。为什么我可以单独打印每个字符,但不能打印整个字符串?
这与内存管理不善有关吗?
这是 CS50 中 pset6 的一部分.
#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;
}
附注,我知道在 for lop strlen(line)-9
中的 -9
中进行硬编码是一种不好的做法。但我不知道如何读取请求的目标 cat.html
中的字符。我知道 header 是由 method SP request-target SP HTTP-version CRLF
指定的(CRLF 又名 \r\n
两个字符吗?)所以 - 9
有效(我认为),但可能不是最好的。
编辑:我编辑了循环,以便在末尾添加一个空终止符。这本来是应该放进去的,但由于我编辑了太多代码,现在它被错误地删除了。但它仍然不起作用。
最佳答案
您的代码具有未定义的行为,因为它写入的内容超出了您分配的空间。
你做这个副本
requestTarget[i] = line[i];
当i
指向line[]
中间的某个位置,但requestTarget
需要较小的索引时。您需要“翻译”索引,或者为目标创建一个单独的索引:
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';
注意:您需要确保 requestTarget
有足够的空间容纳您希望在其中存储的字符,包括空终止符。
关于c - 为什么我可以单独打印每个字符,但不能整体打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33594620/