我知道这与我的 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/