当我试图存储从套接字接收的数据时,我正在将一个指针传递给一个函数以动态分配它。它适用于一个请求,第二个请求通常会导致段错误。Valgrind 抱怨:条件跳转或移动取决于引用我的响应指针的未初始化值。
我怎样才能初始化指针或者我能做些什么来保证它的安全?在主函数中释放它是否正确?
int main(int argc, char **argv) {
char * response;
char readbuf[BUFFSIZE + 1] = "";
//here I read some data into readbuff which I will send to the server below
handle_request_data(readbuf, &response);
//do some stuff with response, send to another socket
free(response); // can I do that?
}
int handle_request_data(char * readbuf, char ** response) {
//create tcp socket, connect to it and send readbuf to server
int recv_total = 0;
char buffer[BUFFSIZE + 1] = "";
*response = malloc(BUFFSIZE + 1);
while ((tmpres = recv(sock_tcp, buffer, BUFFSIZE, 0)) > 0) {
if (recv_total > 0) {
//need more memory for buffer
*response = realloc(*response, BUFFSIZE + recv_total + 1);
}
memcpy(*response + recv_total, buffer, tmpres);
recv_total += tmpres;
}
}
谢谢您的帮助!