![](/img/trans.png)
[英]Char array, string represents a memory address how can i add value to that address?
[英]How can I change the memory address of char*?
我正在處理一個問題,我無法獲得abs_path和查詢數組,這些查詢數組填充有我要在函數解析中傳遞給它們的數據。 在此函數內部的邏輯似乎是正確的,我已對其進行調試,並且兩個數組均填充有正確的數據。 我知道由於條件參數無法更改,因此我沒有在參數中傳遞指向數組(char **)的指針。 關於解決此問題還有其他建議嗎?
#define LimitRequestLine 8190
char abs_path[LimitRequestLine + 1];
char query[LimitRequestLine + 1];
bool parse(const char* line, char* abs_path, char* query)
{
char* method = "GET ";
char* valid_http = "HTTP/1.1";
int index, method_size;
char abs_path_line[LimitRequestLine + 1];
char query_line[LimitRequestLine + 1];
int abs_path_index;
if(strstr(line, "HTTP/")!=NULL && strstr(line, valid_http) == NULL) {
error(505);
return false;
}
//make sure that our method is GET
for(index = 0, method_size = strlen(method); index<method_size; index++) {
if(line[index] != method[index]) {
error(405);
return false;
}
}
//check if request-target starts with '/'
if(line[index]!='/') {
error(501);
return false;
}
for(abs_path_index = 0; index < strlen(line); index++) {
//if there is a quotation mark, then we have a query in request-target
if(line[index] == '?') {
index++;
int query_index;
for(query_index = 0; line[index]!=' '; index++) {
//check if there is quote mark in query
if(line[index] == '"') {
error(400);
return false;
}
query_line[query_index] = line[index];
query_index++;
}
query_line[query_index] = '\0';
}
//assuming that we have not found any '?' mark for query.
if(strstr(line, "?") == NULL) {
query_line[0] = '\0';
}
if(line[index] == ' ') {
int temp = index;
index++;
/*After the space there should be a valid http, if it is not found,
then there is/are spaces in our request-line which is incorrect*/
for(int i=0; i<strlen(valid_http); i++) {
if(line[index] != valid_http[i]) {
error(400);
return false;
}
index++;
}
index = temp;
break;
}
//check if there is quote mark in abs_path
if(line[index] == '"') {
error(400);
return false;
}
abs_path_line[abs_path_index] += line[index];
abs_path_index++;
}
abs_path_line[abs_path_index] += '\0';
abs_path = abs_path_line;
abs_path += '\0';
query = query_line;
printf("abs path is %s\n", abs_path);
printf("query is %s\n", query);
return true;
}
問題是這樣的:
query = query_line;
char *query
表示將傳遞一個指針。 就像其他數字一樣。 這樣想吧。
void set_number(int number) {
number = 6;
}
您希望這能做什么? 不。 與query = query_line
相同。
相反, query
指向大量內存。 您需要將query_line
復制到query
指向的內存中,並希望有足夠的分配空間。
strncpy(query, query_line, LimitRequestLine);
需要調用者分配內存的函數是等待發生的內存問題。 我建議不要修復此問題...
請注意, query
您的功能是不一樣的query
功能外聲明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.