2013-04-04 165 views
-1

在重新分配矢量chunk對象時,我有下面的函數中的內存分配問題,我錯過了什麼以及可能的解決方案是什麼?在for循環中的for循環中的C++內存分配<char> for循環中

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


    } 
+2

究竟是什麼問題呢? – 4pie0 2013-04-04 17:09:57

+0

如果你描述你更詳細 – 2013-04-04 17:10:17

+1

遇到的問題,將有助於我想你應該至少包括關於您的問題,什麼moqane ::文件:: GetFileChunk做更多資訊。 – 2013-04-04 17:11:19

回答

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

應該

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

否則,如果from_pos不是零,你會寫在buffer的末尾,造成可怕的災難。

+0

你是天才THANKS chunk'載體的'的第二環分段錯誤發生了! – 2013-04-04 18:15:26

+0

+1。 – 2013-04-04 18:16:42