简体   繁体   中英

Char* function Never Return value

I'm a newbie of C. Here I write a function to parse http post from browser. Here is my code:

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;
     }

}

So basically, if the procedure goes in the "else" it should return a char pointer to caller. I check the debugger. HttpPostBody_IE has a value but when it return it is a null string.

char* http_body = HTTP_POST_GET_BODY(recieve_buffer);

Anyone has an idea about it?

You declare the pointer-variable HttpPostBody_IE but never allocate memory for it.
The call to strncpy(....) should create a core dump. Try this:

int body_length = HttpPostBodyEnd - HttpPostBody;
HttpPostBody_IE = (char*)malloc(body_length+1);
strncpy(HttpPostBody_IE,HttpPostBody+2,body_length-2);
return HttpPostBody_IE;

Of course, make sure the caller of this functions releases the allocated memory afterwards.
You have a problem in case the function returns from within the if statement. This because no memory is allocated in that case.

You might resolve it this way:

static char HttpPostBody_IE[BIG_ENOUGH_FOR_ANY_SOURCE];
if (....)
{
  ...
}
else
{
  ...
  strncpy(HttpPostBody_IE, ...);
  return (HttpPostBody_IE);
}

Please notice that in this way the variable needs to be static.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM