简体   繁体   中英

C++ FStream throwing exception error

I am using WinSock to download my file from the Internet.

This code here demonstrates me grabbing the content size from the header, than removing the header and writing the rest to the application. FileDownload1.write(...) it throws an Access violation reading error.

Is there anything wrong with this bit of code? (I am use to C style strings, so I am not 100% familiar with C++ standard strings yet.

Here is some of my code:

    DWORD WINAPI DownloadFile(LPVOID VoidAtt){

    ...

    postion = TextBuffer.find("Content-Length: ", 0);
    std::string LengthOfFile = TextBuffer.substr(postion + strlen("Content-Length: "), 7);
    int FileSize = std::stoi(LengthOfFile, nullptr, 10);
    postion = TextBuffer.find("\r\n\r\n", 0);
    std::string memoryblock = TextBuffer.substr(postion + 4, -1);
    std::ofstream FileDownload1;

    FileDownload1.open("64bit1.m4a", std::ios::out | std::ios::binary);
    FileDownload1.write(memoryblock.c_str(), FileSize);
    FileDownload1.close();

    SetWindowTextA(hTextBox, &TextBuffer[0]);
}

If you need it all let me know, (But the full source code is kinda messy because I was just trying to whip up this to figure out how to download a file and write it successfully to the computer.

The second write parameter must be the memory size:

 FileDownload1.write(memoryblock.c_str(), memoryblock.size());

See: fstream::write

You are accessing memoryblock out of its bounds.

Let's say that the content of your TextBuffer is this:

Content-Length:      10\r\n\r\nSomeText

Then let's run through your code:

postion = TextBuffer.find("Content-Length: ", 0);
//position = 0
std::string LengthOfFile = TextBuffer.substr(postion + strlen("Content-Length: "), 7);
//LengthOfFile = "     10"
int FileSize = std::stoi(LengthOfFile, nullptr, 10);
// FileSize = 10
postion = TextBuffer.find("\r\n\r\n", 0);
//position = 23
std::string memoryblock = TextBuffer.substr(postion + 4, -1);
//memoryblock = "SomeText"

The size of data in your memoryblock is 8 (or 9 if you count the \\0 ) yet your FileSize is 10.

Of course this example is created by using invalid data. Yet you should check where the data starts and not just trust the Content-Length . I am not quite sure but if Content-Length also counts the \\r\\n\\r\\n you are skipping you`ll always be of by 4.

You should add a check for the size and finally use this to make sure you are in bounds:

FileDownload1.write(memoryblock.c_str(), memoryblock.size());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM