我一直在试图弄清楚为什么我的一个变量在第二次在gdb中调用时会附加一些垃圾值,但无法弄明白。我已经诊断出这个问题,但不知道如何修复它。
在第一次调用“curl http://localhost:8080/cat.html”时,这是变量返回的内容:
temp = 0x7fffffff9c74 "/cat.html HTTP/1.1\r\n"
request_target = 0x607080 "/cat.html"
abs_path = 0x7fffffffbdd0 "/cat.html"
query = 0x7fffffff9dd0 ""
这很好用,终端确实显示了html文件。但是,我第二次拨打电话是问题出现的地方。
在同一地址的第二次调用中,返回以下变量:
temp = 0x7fffffff9c74 "/cat.html HTTP/1.1\r\n"
request_target = 0x607080 "/cat.html\327\254\367\377\177"
abs_path = 0x7fffffffbdd0 "/cat.html\327\254\367\377\177"
query = 0x7fffffff9dd0 ""
然后我将收到404文件未找到错误。
有人知道我为什么以及在哪里积累所有这些随机字符("\327\254\367\377\177")
?我相信它来自临时变量,但我已经尝试了几个小时来解决它,但我仍然无法做到。
以下是我的“解析”和“加载”功能:
bool parse(const char* line, char* abs_path, char* query)
{
// GET /cat.html?name="Alice" HTTP/1.1
if (strncmp(line, "GET ", 4) != 0)
{
error(405);
return false;
}
else if (line[4] != '/')
{
error(501);
return false;
}
else if (strncmp(strrchr(line, ' '), " HTTP/1.1", 9) != 0)
{
error(505);
return false;
}
char* temp = strchr(line, '/');
int after_length = strlen(strrchr(line, ' '));
char* request_target = malloc(strlen(temp) - after_length);
strncpy(request_target, temp, strlen(temp) - after_length);
if ((strchr(request_target, '"') != NULL || strchr(request_target, ' ') != NULL))
{
error(400);
return false;
}
if (strchr(request_target, '?') == NULL)
{
strcpy(abs_path, request_target);
strcpy(query, "");
}
else
{
int q_length = strlen(strchr(request_target, '?'));
if (q_length != 2)
{
strncpy(abs_path, request_target, strlen(request_target) - q_length);
strcpy(query, &strchr(request_target, '?')[1]);
}
else
{
strncpy(abs_path, request_target, strlen(request_target) - 2);
strcpy(query, "");
}
}
free(request_target);
return true;
}
bool load(FILE* file, BYTE** content, size_t* length)
{
if (file == NULL)
{
error(500);
return false;
}
*content = NULL;
*length = 0;
BYTE buffer[BYTES];
ssize_t bytes = fread(buffer, 1, sizeof(buffer), file);
while (bytes != 0)
{
*content = realloc(*content, *length + bytes);
memcpy(*content + *length, buffer, bytes);
*length += bytes;
bytes = fread(buffer, 1, sizeof(buffer), file);
}
return true;
}