0

I am experimenting with the HTTP protocol using Winsock2. I am working on a function

int recv_data(const char *hostname, char *resp);

The function is meant to send an HTTP HEAD request to a given host and then receive a response. It allocated memory at the pointer resp and copies the response there before returning the total number of bytes received for the response.

Here is my recieve loop:

int recv_data(const char *hostname, char *resp)
{
    int totalRecvd = 0;
    stringstream sStream;
    while (true)
    {
        char buffer[MAX_HEADER_SIZE];
        int retValue = recv(s, buffer, MAX_HEADER_SIZE, 0);
        if (retValue == 0)
            break;  // connection has been closed
        else if (retValue == SOCKET_ERROR)
            throw RecvException("http_headreq() unable to receive data");
        else    //
        {   
            buffer[retValue] = 0; // append null terminator
            sStream << buffer;    // dump buffer into stream
            totalRecvd += retValue + 1; // tally received bytes
        }
    }

    /** Allocate and read entire read stream into memory */
    resp = new char[totalRecvd + 1];
    strcpy(resp, sStream.str().c_str());
    return totalRecvd);
}

All of this works just fine and all and if I output resp at this point it outputs just fine. I just have a problem if I try to output resp after the function has returned apparently. I do not believe this should be how things normally go and if I am not mistaken I believe it has something to do with me using the stringstream to temporarily store the response. I think I have read somewhere about the data that stringstream collects going out of scope.

I was hoping that I could have this function set up this way where the caller can just pass in a char* and the function will allocate the correct amount of memory (which is determined at runtime depending on the host and the number of bytes returned by recv(). Is there anyway for me to get a permanent copy from a stringstream in memory as a char array with the pointer being bad after the function returns and the stringstream goes out of scope?

[EDIT]: Here is the solution posted below incorporated into my problem, anyone looking to reuse this for Winsock2 proramming have at it, seems to work well. Will recv data from the server until the connection is closed when recv() returns 0. The solution is passing in a reference to the pointer, because the new operator changes the pointer and that change is not reflected after the function returns unless it is passed in by reference.

int recv_data(SOCKET s, char *&data)
{
    int totalRecvd = 0;
    std::stringstream sStream;
    while (true)
    {
        char buffer[MAX_HEADER_SIZE];
        int retValue = recv(s, buffer, MAX_HEADER_SIZE, 0);
        if (retValue == 0)
            break;  // connection has been closed
        else if (retValue == SOCKET_ERROR)
            throw RecvException("http_headreq() unable to receive data");
        else    //
        {   
            buffer[retValue] = 0; // append null terminator
            sStream << buffer;    // dump buffer into stream
            totalRecvd += retValue + 1; // tally received bytes
        }
    }

    /** Allocate and read entire read stream into memory */
    data = new char[totalRecvd + 1];
    strcpy_s(data, totalRecvd, sStream.str().c_str());
    data[totalRecvd] = 0;
    return totalRecvd;
}
3
  • 2
    sStream indeed goes out of scope, however the memory pointed to by resp doesn't. Can you provide a short, self-contained example? May 17, 2012 at 0:26
  • @OliCharlesworth I edited the code to more clearly convey what I am trying to do. Outside of this function the caller declares a char *data = NULL and passes it into resp, when the function returns however there is a bad ptr.
    – Cory Gross
    May 17, 2012 at 0:41
  • Use std::string and boost::asio -> problem solved.
    – Puppy
    May 17, 2012 at 0:41

2 Answers 2

3

resp is a local variable in the http_req function. Updating the value of resp will have no effect outside of http_req. This line:

resp = new char[totalRecvd + 1];

will have only local effect.

Try this signature:

int http_req(const char *hostname, char *&resp);


Even better, try returning the data in a C++ way:

std::string http_req(const std::string& hostname) {
    ...
    return sStream.str()
}
3
  • Thank you so much, this is strange but I have never seen this before. This is exactly what I was trying to do, just didn't think this would work. Is there any disadvantage to returning data this way? If I allocate a certain amount of memory at the position pointed to by resp and then the function returns, and I print resp. Can I delete resp afterwards normally, will it know how much data to delete?
    – Cory Gross
    May 17, 2012 at 0:33
  • I would use std strings, but I've written a lot of code for this so far and none of it uses strings, was going to keep it going if possible
    – Cory Gross
    May 17, 2012 at 0:34
  • In my first example, yes, you must invoke delete[] at some point on the pointer variable that was passed-by-reference to http_req. Yes, delete[] will know how much data to delete.
    – Robᵩ
    May 17, 2012 at 0:35
0

If you alter your code to use std::string and boost::asio, you will no longer suffer from memory management problems.

2
  • I should have written this in the OP. I do not have anything personal against using std::string. I love using the std lib and do all the time. But this is kind of a personal learning thing and low-level memory management is high on the list. I would simply have a std::string parameter but I have written a lot of code using only char data so I was going to keep it in line with that if possible.
    – Cory Gross
    May 17, 2012 at 1:09
  • std::string is better than manual memory management in every way. You will consistently have bugs the manual way, no matter how often you do it. It is good to learn how to do it properly the manual way, but you should then learn how to do it properly the c++ way, and always do it that way going forward.
    – Jimbo
    Sep 30, 2013 at 4:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.