Send a variable on the heap to another thread - c++

I have a strange problem in C++. An address of a Boolean gets "destroyed" but it doesn't get touched. I know that there are better ways to accomplish what I try to do, but I want to know what I do wrong.
I have a main class; this main class contains a vector of another class. There is a strange problem when a new instance gets created of this object.
This is how my code works:
There will start a thread when the constructor gets called of the β€œ2nd” object. This thread gets as Parameter a struct. This is the struct:
struct KeyPressData
{
vector<bool> *AutoPressStatus;
vector<int> *AutoPressTime;
bool * Destroy;
bool * Ready;
};
The struct gets filled in the constructor:
MultiBoxClient::MultiBoxClient()
{
//init data
DestroyThread = new bool;
ReadyThread = new bool;
AutoThreadData = new KeyPressData;
//Reseting data
*DestroyThread = false;
*ReadyThread = false;
//KeyPressData configurating
AutoThreadData->AutoPressStatus = &AutoPressStatus;
AutoThreadData->AutoPressTime = &AutoPressTime;
AutoThreadData->Destroy = DestroyThread;
AutoThreadData->Ready = ReadyThread;
//Start the keypress thread
CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)AutoKeyThread,AutoThreadData,NULL,NULL);
}
This is the defenition of MultiBoxClient:
class MultiBoxClient
{
private:
HWND ClientHandle;
vector<bool> KeyPresses;
vector<bool> AutoPressStatus;
vector<int> AutoPressTime;
KeyPressData * AutoThreadData;
bool * DestroyThread;
bool * ReadyThread;
public:
MultiBoxClient();
MultiBoxClient(HWND Handle);
~MultiBoxClient();
void EditClient(HWND Handle);
void SendKeypress(vector<bool> KeyStatus);
void SendKeyCombination(unsigned int id);
void AutoCast(int Key,unsigned int Time,bool status);
bool IsAlive();
};
MultiBoxClient is created this way:
int main()
{
MultiboxControler * MainControler = new MultiboxControler;
while(true)
{
Sleep(1000);
}
delete MainControler;
return false;
}
As long as the constructor is running will the program run fine. But when the constructor closes the address of the AutoThreadData->Destroy will get corrupted. The program will crash when I call the value of the pointer.
 
void WINAPI AutoKeyThread(void * ThreadData)
{
KeyPressData * AutoThreadData = (KeyPressData*)ThreadData;
while(true)
{
if(*AutoThreadData->Destroy == true) //CRASH
{
*AutoThreadData->Ready = true;
return;
}
Sleep(100);
}
}
What did I test:
I logged the address of the AutoThreadData and the AutoThreadData->Destroy when the constrcutor is running and clossed; the AutoThreadData address is equal to AutoThreadData when the constructor is closed. So there is no problem here.
The address of AutoThreadData->Destroy gets destroyed when the constructor is closed. But how can this happen? The Boolean is on the heap and the KeyPressData struct (AutoThreadData) is on the heap.
Destroy before: 00A85328
Destroy after: FEEEFEEE
Can someone maby explain why this crash?
I know that I can send a pointer to my class to the thread. But I want to know what goes wrong here. That way I can learn from my mistakes.
Could someone help me with this problem?

I guess that you made a mistake with the vector, use a class pointer, instead of the class itself, like this:
vector<class*> //instead of vector<class>

0xFEEEFEEE is an indication of freed memory. That is, you AutoThreadData was deleted, and it was not on your worker thread which is in endless loop. So, it has to be your main thread and perhaps destructor, which you did not show.
Whereever you destroy/free your KeyPressData instance, comment this out or set a breakpoint there to find out where it is taking place.

Related

Class requiring itself as pointer variable, cannot allocate memory

Im trying to link one display to another display using c++. For instance
void funcA(){
Display greenScreen;
Display redScreen;
greenScreen.setChild(redScreen);
}
Here's the class implementation:
class display{
public:
display* child = nullptr;
void setChild(display);
}
Implementation of setChild:
void setChild(display childnode){
child = &childnode;
}
I thought this would work, but when i tried to retrieve greenScreen's child, my app crashed. Any help would be greatly appreciated!
This is passing childnode by value: a copy is made, and you're setting this->child to the address of the copy. But the copy only lives while setChild is executing, so when it returns, you're left with a dangling pointer, causing undefined behaviour (probably crashing).
You must pass the address of childnode instead:
void setChild(display *childnode){
child = childnode;
}

Is there a problem with this class' constructor/destructor?

Im using this class in a larger function which isn't terminating properly.
I've had to resort to commenting out the algorithm one chunk at a time to narrow down where the problem is beginning.
The whole thing works as written but ultimately terminates in error and terminates the main() that is calling it.
Anyways, when I instantiate this class, the problem begins. Im assuming it must be a problem with the destructor, causing the error when the object falls out of scope.
Here is the class definition as well as the constructor/destructor:
class Entry
{
private:
int act_count; //number of activities for generating array MUST BE DETERMINED BEFORE INSTANTIATION
int ex_count; //number of expenditures for generating array
public:
Entry(int, int); // constructor
~Entry(); // destructor
string date; // functions like a title
Activity * act_arr; // pointer to an array of activities
Expenditure * ex_arr; // pointer to an array of expenditures
// list of member functions
};
struct Activity
{
public:
string a_name;
float time;
};
struct Expenditure
{
public:
string e_name;
float price;
};
Constructor:
Entry::Entry(int a_count, int e_count)
{
// initialization of basic members
date = day_o_year();
act_count = a_count;
ex_count = e_count;
// allocation of array space
act_arr = new Activity[act_count];
ex_arr = new Expenditure[ex_count];
}
Destructor:
Entry::~Entry()
{
// prevents memory leaks when object falls out of scope and is destroyed
delete act_arr;
delete ex_arr;
}
Are there any egregious errors here? I hope this isn't too much code to pique some interest.
Thanks in advance.
For starters, I think you need this (delete[] array):
Entry::~Entry() {
// prevents memory leaks when object falls out of scope and is destroyed
delete[] act_arr;
delete[] ex_arr;
}
But besides that, exactly what do you mean by "isn't terminating properly"?
Q: Do you have a stack trace/core dump?
Q: Have you stepped through code with the debugger?
Q: Do you have a specific error message you can copy/paste into your post?

c++ correct deletion of structs and pointers

I have a question regarding how to correctly delete structs and it's respective pointers declared inside.
I have extracted an example from a project i have running and it doesn't seem to work correctly, the code doesn't crash but it seems i have some "memory leaks". I'm not sure that is the right wording. The issue is that the values is not really reset and are kept in the memory next time i initiate a class.
Sudocode below:
Header:
ProgramHeader.h
class ClassA : public publicClassA
{
public:
ClassA(void);
virtual ~ClassA();
private:
struct ApStruct{
struct
{
float *refA[2];
float *refB[2];
float *pVarA;
} fR;
struct
{
float *refA[2];
float *refB[2];
float *pVarA;
} f1kHz;
};
ApStruct* GetApStruct;
}
Program:
Program.cpp
#include "ProgramHeader.h"
ClassA::~ClassA()
{
//EDIT i did a typo my looks like this:
//delete ApStruct; //Wrong code
delete GetApStruct; //Corrected - however still not working
}
main()
{
GetApStruct = new ApStruct();
//Do Code
}
Hope it all makes a bit sense,
EDIT:
I have updated one wrong line in the code - however the question still remains the same. I will have a look at below to understand before i implement a solution.
EDIT 24/10/2015
I have been trying out a few of the suggestions below and im not able to find a solution to my issue, i must admit i also have difficulties to narrow it down what could cause it.
My code is part of a DLL. The code wraps some source code im not in control of, and therefore i have limited options how i init using constructors and new on pointers.
The reason i still think i have memory leak issues is if i add a "magic float" in my code the output of my functions change, even the float is not used anywhere - it is just declared.
I get different results when:
Calling InitCode - once!
then i will call CallCode multiple time - doing my calculations
Destruct the instance of the class
When i repeat the above again i get different result from the first time i run the code but afterwards it stays the same.
If i include the magic line all seems to work???
Updated SudoCode:
Program.cpp
#include "ProgramHeader.h"
ClassA::~ClassA()
{
//EDIT i did a typo my looks like this:
//delete ApStruct; //Wrong code
delete GetApStruct; //Corrected - however still not working
}
main()
{
void initCode()
{
GetApStruct = new ApStruct();
float InitValue = 0.F
//Magic line:
float magicLine = 123456.f; //If this line is commented out i get different results in my code
//End Magic Line
fr.refA[0] = &InitValue;
fr.refA[0] = &InitValue;
fr.refA[0] = &InitValue;
fr.pVarA = &InitValue;
...
}
void CallCode()
{
float CallValue = 123.F
//Magic line:
float magicLine = 123456.f; //If this line is commented out i get different results in my code
//End Magic Line
fr.refA[0] = &CallValue;
fr.refA[0] = &CallValue;
fr.refA[0] = &CallValue;
fr.pVarA = &CallValue;
...
}
}
Thanks guys for you support,
Thomas
I would recommend something like the following for allocation and cleanup...
#include <iostream>
using namespace std;
class ClassA
{
public:
ClassA(void);
virtual ~ClassA();
private:
struct ApStruct {
struct
{
float *refA[2];
float *refB[2];
float *pVarA;
} fR;
struct
{
float *refA[2];
float *refB[2];
float *pVarA;
} f1kHz;
};
ApStruct* GetApStruct;
};
ClassA::ClassA(void) {
GetApStruct = new ApStruct{};
GetApStruct->fR.refA[0] = new float{ 1.f };
GetApStruct->fR.refA[1] = new float{ 2.f };
GetApStruct->fR.refB[0] = new float{ 3.f };
GetApStruct->fR.refB[1] = new float{ 4.f };
GetApStruct->fR.pVarA = new float { 0.f };
// do same for struct f1kHz
// ...
cout << "Construction" << endl;
}
ClassA::~ClassA()
{
if (GetApStruct != nullptr) {
if (GetApStruct->fR.refA[0] != nullptr) {
delete GetApStruct->fR.refA[0];
GetApStruct->fR.refA[0] = nullptr;
}
if (GetApStruct->fR.refA[1] != nullptr) {
delete GetApStruct->fR.refA[1];
GetApStruct->fR.refA[1] = nullptr;
}
if (GetApStruct->fR.refB[0] != nullptr) {
delete GetApStruct->fR.refB[0];
GetApStruct->fR.refB[0] = nullptr;
}
if (GetApStruct->fR.refB[1] != nullptr) {
delete GetApStruct->fR.refB[1];
GetApStruct->fR.refB[1] = nullptr;
}
if (GetApStruct->fR.pVarA != nullptr) {
delete GetApStruct->fR.pVarA;
GetApStruct->fR.pVarA = nullptr;
}
// do same for struct f1kHz
// ...
// finally
delete GetApStruct;
GetApStruct = nullptr;
}
cout << "Destruction" << endl;
}
int main() {
{
ClassA a;
}
system("pause");
return 0;
}
Well when you create a structure/class object, it holds the variables and pointers in that object memory area( say an object occupies some space in memory. Let's call it a box). Those pointer variables when initialized with new() or malloc(), are given space outside of that box in which the object's data resides. Those pointers now point to some memory area that is outside of that object's memory area. Now when the object is destructed, that space occupied by object (as we called it the box) is destroyed accompanying the pointer variables. The memory area pointed by the pointers is still in there in program/process memory area. Now we have no clue what's it address or where it lies. That's called memory leak. To avoid this situation, we need to de-allocate the memory referenced by pointers using delete keyword. We're free to go now. I tried to illustrate it with a simple graphic below. ObjectA box illustrates the area occupied by it in the memory. Note that this container/box holds the local varialbes including pointer. The pointer points to some memory location, say 0xFFF... and is illustrated by green line. When we destroy ObjectA, It simply destroys everything in it including 0xFFF address. But the memory located on 0xFFF is still allocated in the memory. A memory leak.
In your destructor, de-allocate memory explicitly using delete keyword. Whoa! We saved the memory.
From Wikipedia Resource Acquisition Is Initialization
Resource Acquisition Is Initialization (RAII) is a programming idiom used prominently in C++. In RAII, resource acquisition is done during object creation, by the constructor, while resource release is done during object destruction, by the destructor. If objects are destroyed properly, resource leaks do not occur.
So you can new the memory used for pointers in constructor and release them in destructor:
ClassA::ClassA(void) {
GetApStruct = new ApStruct;
GetApStruct->fR.refA[0] = new float{ 1.f };
GetApStruct->fR.refA[1] = new float{ 2.f };
}
ClassA::~ClassA(void) {
delete []GetApStruct->fR.refA;
delete GetApStruct;
}
Alright, let me be direct:
If you are using new or delete, you are doing it wrong.
Unless you are an experienced user, or you wish to implement a low-level side project, do not ever use new and delete.
Instead, use the existing standard classes to handle memory ownership, and just avoid heap-allocation when it is unnecessary. As a bonus, not only will you avoid memory leaks, but you will also avoid dangling references (ie, using memory after deleting it).
class ClassA : public publicClassA {
public:
private:
struct ApStruct{
struct
{
float refA[2];
float refB[2];
float pVarA;
} fR;
struct
{
float refA[2];
float refB[2];
float pVarA;
} f1kHz;
};
ApStruct GetApStruct;
}
And yes, in your case it is as simple as removing the pointers. Otherwise, if you want dynamic arrays (ie, arrays whose length is unknown at compile-time) use std::vector.

Evaluating vector::empty() is crashing the program

I'm currently writing an extension of another program (Specificly, of a game) and i've been stuck on solving the following problem for hours now.
Any time a player (client) connects to the game server, the OnClientConnected(int client_number); function is called. In this function, i create an instance of a CPlayer class that stores player information, such as health, speed and any other data i might require. This instance, is then stored by the following class:
class CPlayerManager
{
std::vector<Player*> *player_list;
public:
CPlayerManager();
~CPlayerManager();
void AddPlayer(client_id)
*CPlayer GetPlayerInstance(client_id);
}
CPlayerManager()
{
player_list = new std::vector<Player*>;
}
~CPlayerManager()
{
delete player_list;
}
void CPlayerManager::AddPlayer(client_id)
{
CPlayer *player = new CPlayer(client_id);
player_list->push_back(player);
}
void *CPlayerManager::GetPlayerInstance(client_id)
{
if(player_list->empty())
{
return NULL;
}
for(std::vector<CPlayer*>::size_type i = 0; i != player_list->size(); i++)
{
int client = player_list->at(i)->GetClientId();
if(client_id == client)
{
return player_list->at(i);
}
}
return NULL;
}
Original game functions use a client indexes as arguments and return values, so i need to obtain player instances from client indexes all the time. The problem is in the GetPlayerInstance function. This function might be called when NO client has been yet initialized and stored by the CPlayerManager instance, so we might have an empty vector.
Anytime the GetPlayerInstance function is called when the vector is empty, the entire game server crashes. I've been debugging a bit, and i noticed that the program crashes right in:
//Code reaches here
if(player_list->empty())
{
//code does not reach here
return NULL;
}
Doing bool empty = player_list->empty()) works until i evaluate empty on the if statement.
What could be causing this strange crash?
Your CPlayerManager class has no copy assignment operator or copy constructor. So if you ever copy it, deleting one instance will delete the other instance's vector, leading to disaster. (Follow the rule of three.)
Really, this code should be nuked from orbit. You have no need for a pointer to a vector nor do you need a vector of pointers. Both of these things are just asking for trouble.

Help wanted on memory leak - having a multi-threading queue, char buffer and a structure

So I have a boosted queue class that helps multi-threading described here.
In my class declarations I have
//...
struct VideoSample
{
const unsigned char * buffer;
int len;
};
ConcurrentQueue<VideoSample * > VideoSamples;
//...
struct AudioSample
{
const unsigned char * buffer;
int len;
};
ConcurrentQueue<AudioSample * > AudioSamples;
//...
In my class I have a function:
void VideoEncoder::AddFrameToQueue(const unsigned char *buf, int size )
{
VideoSample * newVideoSample = new VideoSample;
VideoSamples.try_pop(newVideoSample);
newVideoSample->buffer = buf;
newVideoSample->len = size;
VideoSamples.push(newVideoSample);
//free(newVideoSample->buffer);
//delete newVideoSample;
}
keeping only one frame in queue is required for my app.
answer provided here on how to delete a structure is not helpful in this case because app crushes.
I have similar code for audio queue.
void VideoEncoder::AddSampleToQueue(const unsigned char *buf, int size )
{
AudioSample * newAudioSample = new AudioSample;
newAudioSample->buffer = buf;
newAudioSample->len = size;
AudioSamples.push(newAudioSample);
url_write (url_context, (unsigned char *)newAudioSample->buffer, newAudioSample->len);
AudioSamples.wait_and_pop(newAudioSample);
//delete newAudioSample;
}
and a function that runs in separate thread:
void VideoEncoder::UrlWriteData()
{
while(1){
switch (AudioSamples.empty()){
case true :
switch(VideoSamples.empty()){
case true : Sleep(5); break;
case false :
VideoSample * newVideoSample = new VideoSample;
VideoSamples.wait_and_pop(newVideoSample);
url_write (url_context, (unsigned char *)newVideoSample->buffer, newVideoSample->len);
break;
} break;
case false : Sleep(3); break;
}
}
}
BTW: to stream media data to url I use ffmpeg's function.
BTW: here code I use for queues:
#include <string>
#include <queue>
#include <iostream>
// Boost
#include <boost/thread.hpp>
#include <boost/timer.hpp>
template<typename Data>
class ConcurrentQueue
{
private:
std::queue<Data> the_queue;
mutable boost::mutex the_mutex;
boost::condition_variable the_condition_variable;
public:
void push(Data const& data)
{
boost::mutex::scoped_lock lock(the_mutex);
the_queue.push(data);
lock.unlock();
the_condition_variable.notify_one();
}
bool empty() const
{
boost::mutex::scoped_lock lock(the_mutex);
return the_queue.empty();
}
bool try_pop(Data& popped_value)
{
boost::mutex::scoped_lock lock(the_mutex);
if(the_queue.empty())
{
return false;
}
popped_value=the_queue.front();
the_queue.pop();
return true;
}
void wait_and_pop(Data& popped_value)
{
boost::mutex::scoped_lock lock(the_mutex);
while(the_queue.empty())
{
the_condition_variable.wait(lock);
}
popped_value=the_queue.front();
the_queue.pop();
}
Data& front()
{
boost::mutex::scoped_lock lock(the_mutex);
return the_queue.front();
}
};
My question is: How to clean up AddSampleToQueue and AddFrameToQueue so that they would not make memory leaks?
BTW: I am quite new to all this C++ shared/auto stuff. So to say a beginner. So please provide code examples that work at least that are integrated into my code - because I provided all my code. So if you know what to do - please try and integrate your knowledge into my example. Thank you. And if you can show me how to do it with no use of shared/auto ptrs I' d be super glad.
use smart pointers: http://www.drdobbs.com/184401507
Use Shared_ptr
If, when the frame is added to the queue, the ownership of the data array is transferred to the sample, free or delete[] it in the sample's destructor.
You also might want to uses a move constructor so you can have a queue of ConcurrentQueue<VideoSample> rather than ConcurrentQueue<VideoSample*>, which would make the samples you're enqueuing and dequeuing automatic.
Or, if you control what is pushing the data onto the queue use a vector or boost::array instead of a C-style array.
It's also a bit odd to use a queue if you really do only ever want one thing to be in it. Having an variable protected by a mutex and a condition variable would do instead.
A lot of other people have suggested shared pointers.
I don't see a reason not to use a shared pointer instead of a queue here. You permit only one frame, after all. They support locking elegantly, and with just a bit of bodging can be made threadsafe and also simple. You don't really have an opportunity for circular references to occur that I can see, so you should be basically okay this way.
Alternatively, this sounds like a job for a nice circular buffer. That way you could just avoid the naked char array all together. Boost implements one elegantly, and with just a bit of primitive synchro you should be able to make it suitable for your purposes. Of particular note is that this would make expanding your application to handle online data processing relatively simple as well.
If you're interested, I'll hack up some example code.
change your function to the below and do similar changes in other place where you are allocating memory.
void VideoEncoder::AddFrameToQueue(const unsigned char *buf, int size )
{
VideoSample * newVideoSample;
if(!VideoSamples.try_pop(newVideoSample))
{
newVideoSample = new VideoSample;
}
else
{
delete buff;
}
newVideoSample->buffer = buf;
newVideoSample->len = size;
VideoSamples.push(newVideoSample);
}
ANd also I cannot stop myself asking this question.. When you want only one item in queue then why do you need queue at all.
First I would change ConcurrentQueue<VideoSample * > VideoSamples;
into
ConcurrentQueue<VideoSample> VideoSamples;
You don't need this pointer. Turn the rest of the pointers to smart pointers and you're all set!
valgrind will help you find nearly any memory leak in your program. Though as others pointed out, you should be using shared_ptrs.
Your code
VideoSample * newVideoSample = new VideoSample;
VideoSamples.try_pop(newVideoSample);
is a memory leak. If try_pop succeeds it would overwrite the pointer in newVideoSample and your reference to the instance created before is lost forever!
I'm not sure I understand it all, but I'll give it a shot anyway.
The AddFrameToQueue function
So apparently you want a single frame in queue at a time, which means you probably don't need a queue at all. Anyway : either there isn't already a frame in queue and you should create a new one, or there is and you should overwrite its buffer and len fields :
void VideoEncoder::AddFrameToQueue(const unsigned char *buf, int size )
{
VideoSample * newVideoSample = 0;
if (!VideoSamples.try_pop(newVideoSample))
{
// Nothing in queue yet : we allocate a whole new VideoSample
newVideoSample = new VideoSample;
}
else
{
// Here, you want to release newVideoSample->buffer depending on
// the way it was allocated in the first place : free if malloc'ed,
// delete if new'ed...
}
newVideoSample->buffer = buf;
newVideoSample->len = size;
VideoSamples.push(newVideoSample);
// The VideoSample pointer has been pushed in the queue : we must no delete
// it in order for the queue to keep containing a valid pointer
}
The AddSampleToQueue function
Why is there a wait_and_pop at the end of this function : isn't the pop supposed to take place in UrlWriteData ? I really don't understand this part. If the goal is to have a single item in queue, you probably don't need a queue (episode 2), but I guess you could use the same code as AddFrameToQueue.
The UrlWriteData function
Here, data is actually being removed from the queue, so you want to release it as soon as you're done writing.
void VideoEncoder::UrlWriteData()
{
while(1){
switch (AudioSamples.empty()){
case true :
switch(VideoSamples.empty()){
case true : Sleep(5); break;
case false :
VideoSample * newVideoSample;
VideoSamples.wait_and_pop(newVideoSample);
url_write (url_context, (unsigned char *)newVideoSample->buffer, newVideoSample->len);
// Release newVideoSample->buffer using free if malloc'ed, delete
// if new'ed...
delete newVideoSample;
break;
} break;
case false : Sleep(3); break;
}
}
}
That's the best I can't tell you without trashing the whole thing and go for smart pointers, RAII and all those things that make C++ :)