In below code, the sv object in main function is created on stack but doesn't go out of scope. But I am getting occasional heap corruptions. When run under valgrind I see illegal read/write warnings
However if I create sv object on heap, I didn't see any issues.
CODE BELOW
#include <iostream>
#include <thread>
#include <functional>
#include <mutex>
mutex m;
struct SharedVec
{
public:
std::vector<int> v;
};
void check(SharedVec * sv)
{
while (true) {
m.lock();
sv->v.push_back(2);
m.unlock();
}
}
int main()
{
SharedVec sv; // this shared object which has vector member causing heap corruption
//although in scop
//SharedVec * sv = new SharedVec(); // if i create on heap, no issues seen
std::thread t(check, std::bind(&sv));
while (true)
{
std::vector<int> tmp;
m.lock();
tmp = sv.v;
sv.v.clear();
m.unlock();
}
t.join(); // Wait for the thread to finish
return 0;
}