简体   繁体   中英

c++ memory allocation in a for loop in vector<char> in a for loop

I have a memory allocation problem in the following function when reallocating the vector chunk object, what am I missing and what could be the possible solution?

    public:
    void send_FILE(std::string file_id, std::string file_path)
    {

        char* fid = moqane::number2string::To_CharArray(file_id);
        int fid_length = moqane::number2string::CharArray_Length(fid);
        const int step = packet_->BUFFER_SIZE;
        long total_length = boost::filesystem::file_size(file_path);


        for (int x = 0; x < total_length; x += step)
        {
            if ((x + step) <= total_length)
            {
                std::vector<char> chunk = moqane::file::GetFileChunk(file_path, x, x+step);
                write_FILE_CHUNK(fid, fid_length, chunk);

            }
            else
            {
                std::vector<char> chunk = moqane::file::GetFileChunk(file_path, x, total_length);
                write_FILE_CHUNK(fid, fid_length, chunk );
            }
        }
    }

EDIT

This the moqane::GetFileChunk() function

 public:
    static std::vector<char> GetFileChunk(std::string file_path, int from_pos, int to_pos)
    {
        boost::filesystem::ifstream file;
        if (file)
        {
            file.open(file_path.c_str(),std::ios::in|ios::binary);
            file.seekg(from_pos,std::ios::beg);

            std::vector<char> buffer(to_pos - from_pos);
            file.read(&buffer[0], to_pos);



             return buffer;
        }


    }
file.read(&buffer[0], to_pos);

should be

file.read(&buffer[0], to_pos - from_pos);

Otherwise, if from_pos isn't zero, you'll write beyond the end of buffer , causing dreadful calamities.

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