【问题标题】:C malloc increase buffer sizeC malloc 增加缓冲区大小
【发布时间】: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);    
}   

【问题讨论】:

标签: c http malloc buffer


【解决方案1】:

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

变化:

char *rec = new char[10000];

收件人:

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

看看有没有区别。

【讨论】:

  • 确实如此。 new char[10000] 也不是有效的 C,而且这个问题上也没有 C++ 标签。
  • 具体来说,char *x = new char(); 将编译为 C++(将 null 分配给 x,而 new char() 永远不会这样做),而 char *x = new char[3]; 不会编译。 #define new WHAT_LANGUAGE_IS_THIS 可能会更好,或者最好的是#ifdef __cplusplus \n #error "Don't compile C code with a C++ compiler, you muppet" \n #endif
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 2014-02-21
    相关资源
    最近更新 更多