0

I'm currently doing a program in c++ related to windows socket. On the part where I'm going to receive the answer from an http request and put the data inside of a buffer, I declared the size of the buffer which is 10000, my question is how can I allocate memory during runtime and will no need to declare the size of the buffer during compiling?

Initial code for receiving the data from http request:

char buffer[10000];

// Receiving and Displaying an answer from the Web Server
    ZeroMemory(buffer, sizeof(buffer));
    while ((dataLen = recv(Socket, buffer, sizeof(buffer), 0) > 0))
    {
        int i = 0;
        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
            cout << buffer[i];
            i += 1;
        }
    }

thanks for the help!

frrelmj
  • 9
  • 4
  • Please, use `std::vector`. – Swordfish Nov 21 '18 at 03:23
  • hi @Swordfish thanks! also, can I use new and delete operator? – frrelmj Nov 21 '18 at 03:34
  • *can I use new and delete operator?* -- Over using `vector`? That's like asking "can I use candles instead of a flashlight?" – PaulMcKenzie Nov 21 '18 at 03:36
  • Of course you can try and shoot yourself in the foot, but you really don't want to. – Swordfish Nov 21 '18 at 03:36
  • Suggestion: replace `buffer[i] >= 32` with `buffer[i] >= ' '`. More portable and the intent is clearer. [Fear the Magic Number.](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad) – user4581301 Nov 21 '18 at 03:39
  • `while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r')` lacks a terminating condition should `buffer` run out of good data before it runs out of whitespace. Remember that TCP is a stream-based, not message-based, protocol and that `recv` will return when it runs out of available data as well as when the buffer is filled. This could be as little as one byte, so you should make better use of `dataLen ` – user4581301 Nov 21 '18 at 03:44
  • Handy reading: [Why should C++ programmers minimize use of 'new'?](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new) It should explain some of the vehemence in the responses to *can I use new and delete operator?* – user4581301 Nov 21 '18 at 03:46

1 Answers1

0

Probably, you want something like this:

std::vector<uint8_t> req_body;

/* temporary buffer */
char buffer[1024];

/* count of read bytes per chunk */
size_t read = 0;

while (read = recv(Socket, buffer, sizeof(buffer), 0))
{
    size_t old_size = req_body.size();

    /* expand body size */
    req_body.resize(old_size + read);

    /* write new chunk of data to body */
    memcpy(req_body.data() + old_size, buffer, read);
}

/* handle request */

req_body.clear();

Also, remind that there are no guarantee for completeness of data. So it is better to wait for 'Content-Length' header, then find end of headers block and wait until full length will be received before clear the body.

kerrytazi
  • 573
  • 4
  • 13