Keith Miller
Keith Miller

Reputation: 1347

RECV Dynamic Memory Allocation

In C I am looking to read the html of a page, but I want the buffer that is holding the data to be dynamic. I know that I will have to do this with a loop and the use of realloc but I'm not quite sure how I would go about doing that. Assuming I have my socket (sock) already open consider the following:

char *buffer = ???, *tmp;  //just my guess I'm fairly certain buffer cannot be NULL considering my recv loop...
int q = 0, c;
int i = 1;       //buffer size

    while(q < i)
{
    c == recv(sock, buffer + q, i - q, 0);
    if(c == SOCKET_ERROR) break;
    i += c;
    tmp = realloc(buffer, i * sizeof(char));
    //if(!tmp) /*not important right now I can add error handling later*/;
    buffer = tmp;      
    q += c;
}

This would be my best guess on how to achieve my goal, but I highly doubt this will work, and I just need some insight or correction.

Upvotes: 2

Views: 1342

Answers (1)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84189

Some bad errors in the code:

c == recv(...

== is a comparison, not assignment, you will ever get either 0 or 1. Then:

tmp = realloc(buffer, i * sizeof(char));

sizeof(char) is 1 by definition, and you have to check the return value against NULL. Also, name your variables something meaningful - will save you a lot of grief later.

Now, you are trying to do something like "post-allocation" - read into a buffer and then extend it to the size you just got - kind of backwards.

Simple solution (one of many):

  • allocate the buffer upfront,
  • read into it in a loop keeping track of the accumulated size (and thus the offset),
  • if you run out of buffer space - re-allocate it to twice the size of the previous one, and continue.

This works most of the timeTM. You might want to add some sanity checks not to gobble all your memory if the other side keeps feeding you data.

Hope this helps.

Upvotes: 4

Related Questions