views:

309

answers:

2

this is part of my code which reads an http response. It's supposed to increase the buffer size if it runs out of room. But i keep getting access violations. It happens when copying the data to the new buffer: memcpy(tmp_alloc, rec, ResponseLength); Any help/suggestions are appreciated.

#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);    
}   
+4  A: 

It's possible that you're corrupting the heap by mixing new[] with free(), which is not supported.

Change:

char *rec = new char[10000];

To:

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

and see if it makes any difference.

Michael Burr
Indeed. Nor is `new char[10000]` valid C, and there's no C++ tag on this question.
Fred Larson
#define new NULL;//
tur1ng
@tur1ng: doesn't work.
Steve Jessop
Specifically, `char *x = new char();` will compile as C++ (assigning null to `x`, which `new char()` never does), whereas `char *x = new char[3];` doesn't compile. `#define new WHAT_LANGUAGE_IS_THIS` might be better, or best of all `#ifdef __cplusplus \n #error "Don't compile C code with a C++ compiler, you muppet" \n #endif`
Steve Jessop
A: 

wouldn't it be better, to have this data as a list of buffers? this way, you dont have to reallocate/copy all data every time you exceed your buffer. you would only need to maintain a single/double linked list

fazo