Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 985
Alberto Avatar asked Aug 06 '26 20:08

Alberto


2 Answers

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.

like image 55
unwind Avatar answered Aug 08 '26 09:08

unwind


&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.

like image 37
Nish Avatar answered Aug 08 '26 09:08

Nish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!