【问题标题】:c++ memory allocation in a for loop in vector<char> in a for loopc++ 在 for 循环中的 vector<char> 中的 for 循环中的内存分配
【发布时间】:2013-04-04 17:06:27
【问题描述】:

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


    }

【问题讨论】:

  • 究竟是什么问题?
  • 如果您更详细地描述您遇到的问题会有所帮助
  • 我认为您至少应该包含有关您的问题以及 moqane::file::GetFileChunk 的作用的更多信息。
  • 没有描述,我只能猜测;但也许write_FILE_CHUNK 存储了指向向量或其内容的引用或指针,并且在向量被销毁后还有其他东西访问它?这是我可以在这里看到的唯一合理可能的内存问题。
  • @MohamedTarek:段错误发生在哪里?您的调试器应该向您显示调用堆栈,并让您检查它试图访问的可疑地址。

标签: c++ memory for-loop vector allocation


【解决方案1】:
file.read(&buffer[0], to_pos);

应该是

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

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

【讨论】:

    猜你喜欢
    • 2015-08-10
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 2013-11-05
    • 2022-10-20
    • 2011-10-18
    • 2021-10-28
    相关资源
    最近更新 更多