【发布时间】:2013-01-31 22:41:39
【问题描述】:
当我试图存储从套接字接收的数据时,我将一个指向指针的指针传递给一个函数以动态分配它。它适用于一个请求,第二个请求通常会导致段错误。 Valgrind 抱怨:条件跳转或移动取决于引用我的响应指针的未初始化值。
如何初始化指针或者我可以做些什么来保证这个安全?在main函数中释放它是否正确?
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;
}
}
感谢您的帮助!
【问题讨论】:
-
在函数末尾添加
*response [recv_total] = '\0';否则缓冲区不会被 NUL 终止。 2)另外:tmpres 可以是-1;应单独处理。 -
什么是缓冲区? readbuf ??