c - 为什么我可以单独打印每个字符,但不能整体打印?

标签 c server cs50

这是服务器实现的一部分,我将在其中遍历请求行 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/

相关文章:

node.js - 如何使用 node.js 设置工作网络上的其他人可以访问的服务器?

c - 如何索引 "struct"成员?如何在 C 中正确访问它们?

c - 无法正确使用fwrite

c - 为什么我的二分查找在未找到元素时返回 "true"?

python - Flask 在被请求太频繁时给出 "error 32 broken pipe"

c - 使用系统调用 read 从文件中读取 double

C 中 strtok 后无法正确计算 CSV 中的元素

c - 将虚拟地址映射回物理地址

java - 为什么这段代码不能在Java中运行?

mysql - Digital Ocean,使用 mySQL workbench 连接数据库