Ili*_*oly 1 c malloc buffer http
这是我读取http响应的代码的一部分。如果空间不足,它应该增加缓冲区大小。但我不断收到访问违规。将数据复制到新缓冲区时会发生这种情况:memcpy(tmp_alloc, rec, ResponseLength); 任何帮助/建议表示赞赏。
#define SERVER_CHUNK 1024
char *rec = new char[10000];
char in_buff[SERVER_CHUNK];
int in_sz,
ResponseLength = 0,
rec_len = 10000;
in_sz = recv(ss,in_buff,SERVER_CHUNK,0);//get the response
while(in_sz > 0)
{
memcpy(rec + ResponseLength,in_buff,in_sz);
ResponseLength += in_sz;
if((ResponseLength + SERVER_CHUNK) > rec_len)
{
char *tmp_alloc = (char*) malloc (ResponseLength + SERVER_CHUNK);
if(!tmp_alloc)
{
printf("failed to alocate memory!\n");
break;
}
memcpy(tmp_alloc, rec, ResponseLength);
free(rec);
rec = tmp_alloc;
rec_len = ResponseLength + SERVER_CHUNK;
}
in_sz = recv(ss,in_buff,SERVER_CHUNK,0);
}
Run Code Online (Sandbox Code Playgroud)
您可能会通过将 new[] 与不支持的 free() 混合来破坏堆。
改变:
char *rec = new char[10000];
Run Code Online (Sandbox Code Playgroud)
到:
char *rec = (char*) malloc( 10000);
Run Code Online (Sandbox Code Playgroud)
看看它是否有任何区别。