【发布时间】:2010-03-09 22:45:27
【问题描述】:
这是我读取 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);
}
【问题讨论】:
-
你可能想看看
realloc(opengroup.org/onlinepubs/007908775/xsh/realloc.html)。 -
或者由于代码使用
new,您可能需要查看std::vector。 -
这应该是 C 还是 C++?
-
它应该是 C. 而 new char[] 是问题