-1

在重新分配向量对象时,我在以下函数中遇到内存分配问题,chunk我缺少什么以及可能的解决方案是什么?

    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 );
            }
        }
    }

编辑

这是 moqane::GetFileChunk() 函数

 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;
        }


    }
4

1 回答 1

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

应该

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

否则,如果from_pos不为零,你会写到结尾之外buffer,造成可怕的灾难。

于 2013-04-04T18:03:49.827 回答