C malloc 增加缓冲区大小

标签 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);    
}   

最佳答案

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

改变:

char *rec = new char[10000];

收件人:

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

看看它是否有任何不同。

关于C malloc 增加缓冲区大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2413189/

相关文章:

c# - 将具有另一个结构数组的结构从 C# 传递到 C (P/Invoke)

Cygwin:由于 stdio putc + 行缓冲而丢失流数据

perl - 如何用 Perl 编写 HTTP 服务器?

c - pthread_self() 返回的线程 ID 与调用 gettid(2) 返回的内核线程 ID 不同

c - 如何停止循环并等待从串行接收到不同的值

php - 尝试从中检索表单数据时,如何将 php 应用于 6 个单独的选择元素?

rest - 返回未找到子资源的状态码

linux - kmalloc() kcalloc() vmalloc() 和 kzalloc() 之间有什么区别?

C-函数参数和指针

c++ - 如何在 C++ 中创建一个位于堆而不是堆栈的数组?