Alberto
Alberto

Reputation: 711

Dynamic memory allocation for socket C

I want to reserve dynamic memory from a socket. The size of the response is variable so I want to use realloc to allocate the proper memory size.

This is the code snippet that takes care of it:

char *ptr = (char*)calloc(sizeof(char),1024);
char *ptr2 = (char*)calloc(sizeof(char),1024);
//printf("aaaaaaa  %p bbbbbbbb",ptr);
int nDataLength;
int i = 0;
while ((nDataLength = recv(Socket, ptr, 1024, 0)) > 0){

    if (i > 0){//prepare in case that the response is bigger than 1024 bytes
        printf("Data len: %d\n", nDataLength);
        printf("%p points toa %d len: %d\n", ptr, *ptr, ((1024 * i) + nDataLength));
        ptr2 = (char*)realloc(ptr2,((1024*i)+nDataLength));
        printf("%p pints toa %d\n", ptr2, *ptr2);
        system("pause");
        memcpy(ptr2, ptr, nDataLength);
    }
    memcpy(ptr2, ptr, nDataLength);
    i++;
}

The problem is that the buffer that I receive from the socket is allways being memcpyed to the same address so I am overwriting the previous buffer. How can I move ptr2 to not overwrite the previous store buffer? It must be somethin like:

memcpy(ptr2+((1024 * i), ptr, nDataLength); but it does not work.

Thank you

Upvotes: 3

Views: 2617

Answers (2)

Nish
Nish

Reputation: 379

&ptr[1024] gives the address after ptr ends. You just have 2 buckets. you need to consume before you add more data to it. If its a TCP socket based protocol (or any stream based), you need to just read the header, the header should have a indication of data size. malloc for that size, consume the data and then go read the next header.

Upvotes: 2

unwind
unwind

Reputation: 400009

First:

  1. Please don't cast the return value of calloc() in C. Or malloc().
  2. Don't use sizeof (char) to "scale" allocations, it's always just 1 so it's pointless.
  3. There's no need to use calloc() if you're going to recv() into the memory anyway.

Your problem is that you keep passing recv() the start of your growing buffer, instead of the next free location to store at. You should have something like put + nTotalLength as the target for recv(), and then do nTotalLength += nDataLength after each successful reception.

Upvotes: 2

Related Questions