I want to return a std::pair<std::vector<int>, double>
from a thread.
The setup is the following:
void* thread_run(void *);
int main(int argc, char* argv[]) {
std::pair<std::vector<int>, double> value;
pthread_t t;
pthread_create(&t, NULL, thread_run, NULL);
// wait
void* out;
pthread_join(t, &out);
value = *(std::pair<std::vector<int>, double> *)out;
free(out);
use(value);
}
void* thread_run(void* arg) {
std::pair<std::vector<int>, double> * out = (std::pair<std::vector<int>, double>*)
malloc(sizeof(std::pair<std::vector<int>, double>));
out->first = calc1();
out->second = calc2();
pthread_exit(out);
}
The problem is that I create a memory leak. Valgrind reports that:
A conditional jump or move depends on unitialised values and points to the allocation
out->first = calc1();
Unitialized value was created by a heap allocation and points to the malloc line.
I am using gcc 5.4.0 & C++ 11 and the pthread library. I need to use pthread. How do I return C++ STL containers correctly to avoid the memory leak.