C malloc增加缓冲区大小

时间:2010-03-09 22:45:28

标签: c http malloc buffer

这是我的代码中读取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);    
}   

2 个答案:

答案 0 :(得分:4)

你可能通过将new []与free()混合来破坏堆,这是不受支持的。

变化:

char *rec = new char[10000];

要:

char *rec = (char*) malloc( 10000);

看看它是否有所不同。

答案 1 :(得分:-1)

将这些数据作为缓冲区列表会不会更好? 这样,每次超过缓冲区时,都不必重新分配/复制所有数据。 你只需要维护单/双链表

相关问题