c - 为什么会出现段错误?

标签 c string loops

我知道这与我的 for 循环有关。已尝试修改它,但无论我为参数输入什么,我仍然会遇到段错误。

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

int
main(int argc, char * argv[])
{
   char* request_target = "/cat.html?q=Alice hej";

   // TODO: extract query from request-target
   char query[20];

   // finds start of query
   char* startofquery = strstr(request_target, "q=");
   if (startofquery != NULL)
   {
       int j = 0;
       for (int i = strlen(request_target) - strlen(startofquery); i  == ' '; i++, j++)
       {
           query[j] = request_target[i];
       }
       request_target[j] = '\0';
   }
   else
   {
       printf("400 Bad Request");
   }

   printf("%s", query);
} 

最佳答案

这一行定义了一个字符串字面量

char* request_target = "/cat.html?q=Alice hej";

写入字符串文字是未定义的行为
你在这里这样做:

request_target[j] = '\0';

改用字符数组

char request_target[] = "/cat.html?q=Alice hej";

此外,如果我理解正确的话,您正试图从 /cat.html?q=Alice hej 中提取 q=Alice。正如其他答案中提到的,您实现的 for 循环存在一些问题 (i == ' ')。并且实际上没有必要。您可以非常简单地复制这部分内容:

char *startofquery = strstr(request_target, "q=");
char *endofquery = strchr(startofquery, ' ');
int querySize = endofquery - startofquery;
if (startofquery != NULL && endofquery != NULL) {
    memcpy(query, startofquery, querySize);
    query[querySize] = '\0';
}

这不太容易出错,而且很可能会表现得更好。在这种情况下,您不需要将 request_target 定义为数组,但我建议将其设为 const,这样如果您尝试编写,您将得到一个有用的编译器错误:

const char *request_target = "/cat.html?q=Alice hej";    

关于c - 为什么会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33804210/

相关文章:

c - 使用参数 C 运行程序

c - 通过 ref 从结构体中的数组传回值

c - Arduino 开发环境 : Print once inside loop

java - 如何从扫描仪获取多个整数输入并将每个整数存储在单独的数组中?

c - 结构和链接列表问题

C malloc 与字符串数组

C 字符串在一个函数中是正确的,在另一个函数中转储垃圾

python - 如何在 Python 中第一次出现字母时拆分字符串?

r - 用于按组 ID 子集数据的 for 循环的更高性能替代方案是什么?

将 char 数组中的内容转换为 C 中的十六进制(例如 : {'5' , 'A' } 到 0x5A)