爲什麼在插入向量後內存已損壞。在下面的程序中,我有一個字符串var的結構(它不是一個指針)。我每次創建一個本地結構對象並分配一個字符串值並將其推送到該向量。在推送到向量後,我正在對本地結構對象進行更改。但是這種變化正在反映在向量結構對象的字符串數據中。推入載體後內存已損壞
#include <iostream>
#include <vector>
#include <string>
#include <memory.h>
using namespace std;
void PushVector(string);
struct thread_info
{
int id;
string threadname;
bool bval;
};
std::vector<thread_info> myvector;
int main()
{
PushVector("Thread1"); // valid data into vector
PushVector("Thread2");
struct thread_info print;
while(!myvector.empty())
{
for(unsigned int index = 0; index < myvector.size(); ++index)
{
print = myvector.at(index);
cout<<"id : "<<print.id<<"\nthread name : "<<print.threadname<<"\nbool value : "<<print.bval<<endl;
}
myvector.clear();
}
return 0;
}
void PushVector(const string str)
{
std::cout << "Push the thread name to vector\n";
struct thread_info thread;
thread.id = 10;
thread.threadname = str;
thread.bval = true;
myvector.push_back (thread); //copying struct obj to vector
char* p = (char*)thread.threadname.c_str();
memcpy(p,"Wrong", 5); //==> Memory corrupting with invalid data after push back. Is it a limitation in C++?
thread.threadname = "blabla"; //trying to corrupt directly to string object
}
O/P: 推線程名稱爲矢量
推線程名稱爲矢量
ID:10
線程名:Wrongd1 ==>內存損壞?爲什麼沒有blabla字符串?
bool value:1
id:10
線程名稱:Wrongd2 ==>內存損壞?爲什麼沒有blabla字符串?
布爾值:1個
你說「即使在」之後,彷彿進入一個向量魔法般地修復所有內存腐敗。 –
這樣跺腳在琴絃記憶中只會導致眼淚 – paulm