I have a C++ Qt static library with two classes - dataprocthread and calcvalue. In the first one, when I call a method from an instance of calcvalue, pointer this
(which references to dataprocthread class) suddenly becomes null
.
This is dataprocthread.h:
class DataProcThread : public QThread
{
Q_OBJECT
public:
DataProcThread(int sarray[9], int val);
signals:
workDone(int result);
private:
int _sarray[9];
int _val;
void run();
};
dataprocthread.cpp:
DataProcThread::DataProcThread(int sarray[9], int val)
{
for (int x = 0; x < 9; x++)
{
_sarray[x] = sarray[x];
}
_val = val;
}
void DataProcThread::run()
{
CalcValue* cv = new CalcValue();
int myval = 0;
for (int i = 0; i < 100; i++)
{
myval = cv->processData(this->_val);
if (this->_sarray[0] != myval)
{
//do something
}
}
emit workDone(intValue);
}
calcvalue.h:
class CalcValue
{
public:
CalcValue();
int processData(int someval);
};
calcvalue.cpp:
CalcValue::CalcValue()
{
}
int processData(int someval)
{
//do something and return int value
}
When I run this code, it suddenly recieves signal "Segmentation fault". Using debugger, I found that the problem in DataProcThread::run()
function: when I call cv->processData
function, all works good. But on the next line (if (this->_sarray[0] != myval)
), this
pointer becomes null
(I can see it in Locals window), therefore, I can't access this->_sarray
variable.
In case it is important, that's how I start the thread (from another class outside my library):
DataProcThread* thread = new DataProcThread(sarray, val);
QObject::connect(thread, SIGNAL(workDone(int)), this, SLOT(collectWork(int)));
thread->start();
What I am doing wrong?
The problem, as was pointed out in comments, took place in processData
function: it was writing over memory.
I simply used strncpy
instead of strcpy
and the problem gone (here is a good explanation about this).