【发布时间】:2021-12-14 03:51:07
【问题描述】:
我正在尝试使用一些自定义库来制作 HTTP 响应。库函数需要一个指向自定义结构HttpHeader 的数组的指针。代码下方是手册页中的 sn-p。我想知道如何初始化它,以便Content-Length 填充名称和一个值填充值,然后数组中的下一个HttpHeader 是手册页指定的NULL 指针。以下是我目前拥有的代码,但我的系统在为标头分配原始内存时出错:
错误:“HttpHeader”之前的预期表达式
HttpHeader** headers = malloc(sizeof(**HttpHeader));
如何解决这个错误?
我的代码:
void populate_header(HttpHeader** headers, char* value) {
headers[0]->name = malloc(sizeof(char) * strlen("Content-Length"));
headers[0]->value = malloc(sizeof(char) * strlen(value));
strcpy(headers[0]->name, "Content-Length");
strcpy(headers[0]->value, value);
}
char* process_address(char** addrContents) {
HttpHeader** headers = malloc(sizeof(*HttpHeader));
char* body = NULL;
char* response = NULL;
if (strcmp(addrContents[1], "validate") == 0) {
populate_header(headers, "0");
if (!check_expression(addrContents[2])) {
response = construct_HTTP_response(400, "Bad Request", headers, body);
} else {
response = construct_HTTP_response(200, "OK", headers, body);
}
} else if (strcmp(addrContents[1], "integrate") == 0) {
if (!check_expression(addrContents[2])) {
populate_header(headers, "0");
response = construct_HTTP_response(400, "Bad Request", headers, body);
} else {
response = construct_HTTP_response(200, "OK", headers, body);
}
} else {
populate_header(headers, "0");
response = construct_HTTP_response(400, "Bad Request", headers, body);
}
//printf("Response: %s\n", response);
return response;
}
手册页:
headers
points to an array of HttpHeader* (see below), each containing the name of value of a HTTP header. The last entry in headers will be a NULL
pointer.
HttpHeader
A HttpHeader is defined as follows:
typedef struct {
char* name;
char* value;
} HttpHeader;
Memory for name and value is allocated separately.
【问题讨论】:
-
正确答案取决于
construct_HTTP_response是否拥有headers指向的任何东西。 -
您没有在
populate_header中分配足够的空间。因为 C 字符串以空字节结尾,所以需要分配 strlen + 1。更好的是,使用strdup。