我是C的新手。这里我编写了一个从浏览器解析http post的函数。这是我的代码:
char* HTTP_POST_GET_BODY(char* HttpPost){
char* HttpPostBody = strstr(HttpPost,"\r\n\r\n");
HttpPostBody = HttpPostBody + 4;
if(strcmp(HttpPostBody,"\r\n\r\n") != 0 && strcmp(HttpPostBody,"") != 0){
return HttpPostBody;
}
else{
char* HttpPostBody_IE;
HttpPostBody = strstr(HttpPost,"::");
char* HttpPostBodyEnd = strstr(HttpPost,"HTTP/1.1");
int body_length = HttpPostBodyEnd - HttpPostBody;
strncpy(HttpPostBody_IE,HttpPostBody+2,body_length-2);
return HttpPostBody_IE;
}
}
所以基本上,如果程序进入“else”,它应该返回一个指向调用者的char指针。我检查调试器。 HttpPostBody_IE有一个值但是当它返回时它是一个空字符串。
char* http_body = HTTP_POST_GET_BODY(recieve_buffer);
有人对此有所了解吗?
答案 0 :(得分:2)
您声明指针变量HttpPostBody_IE
但从不为它分配内存
对strncpy(....)
的调用应该创建一个核心转储。
试试这个:
int body_length = HttpPostBodyEnd - HttpPostBody;
HttpPostBody_IE = (char*)malloc(body_length+1);
strncpy(HttpPostBody_IE,HttpPostBody+2,body_length-2);
return HttpPostBody_IE;
当然,请确保此函数的调用者之后释放已分配的内存
如果函数从if
语句中返回,则会出现问题。这是因为在这种情况下没有分配内存。
你可以这样解决它:
static char HttpPostBody_IE[BIG_ENOUGH_FOR_ANY_SOURCE];
if (....)
{
...
}
else
{
...
strncpy(HttpPostBody_IE, ...);
return (HttpPostBody_IE);
}
请注意,这样变量必须是静态的。