繁体   English   中英

向量中for循环中的c ++内存分配 <char> 在for循环中

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

重新分配矢量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;
        }


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

应该

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

否则,如果from_pos不为零, from_pos超出buffer的末尾进行buffer ,从而导致严重的灾难。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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