MySQL Connector/C++ error in while loop - c++

void dataProcess::loginProcess(byte* packet, uint16_t length)
{
unique_ptr<ResultSet> res;
unique_ptr<Statement> stmt;
byte idPacket[4] = {packet[9], packet[8], packet[7], packet[6]};
uint32_t id, account_id;
string account_pass, account_type;
id = decodeToInt(idPacket, 4);
account_pass = decodeToChar(packet, 14, length - 1);
account_type = decodeToChar(packet, 10, 11);
stmt.reset(this->con->createStatement());
res.reset(stmt->executeQuery("SELECT * FROM account_info"));
while(res->next())
{
account_id = res->getUInt("id");
if(lowerCase(account_type).compare("ts") == 0)
{
if((account_id == id) && (account_pass.compare(res->getString("password")) == 0))
{
sendPacket("F4440300010300");
}
else
{
wrongPass();
}
}
else
{
wrongPass();
}
}
}
so the above function is being called once in each iteration of an infinite while loop and the function always failed at the 2nd iteration. I think this is somehow related to the deletion of the ResultSet object at the first iteration because when I try using a normal pointer and using the delete statement the same problem occurs but if I remove the delete it can get through the 2nd iteration but I'm quite sure that the ResultSet needs to be deleted according to the example on MySQL website. I am quite new to mysql Connector/C++ so I am very unsure to what is causing this problem. From debugging it appears to fail at this line on the second iteration.
res.reset(stmt->executeQuery("SELECT * FROM account_info"));
This is the error that appears after the program enters the second iteration
Error in `./server': free(): invalid size: 0x00007f8214004ca0 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x790cb)[0x7f8219aa70cb]
/lib/x86_64-linux-gnu/libc.so.6(+0x8275a)[0x7f8219ab075a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7f8219ab418c]
/usr/lib/x86_64-linux-gnu/libmysqlcppconn.so.7(_ZN5boost20checked_array_deleteIc EEvPT_+0x1f)[0x7f821a9397df]
/usr/lib/x86_64-linux-gnu/libmysqlcppconn.so.7(_ZN5boost12scoped_arrayIcED1Ev+0x 1b)[0x7f821a9390b5]
/usr/lib/x86_64-linux-gnu/libmysqlcppconn.so.7(_ZN3sql5mysql15MySQL_ResultSetC2E N5boost10shared_ptrINS0_9NativeAPI22NativeResultsetWrapperEEENS2_8weak_ptrINS4_2 3NativeConnectionWrapperEEENS_9ResultSet9enum_typeEPNS0_15MySQL_StatementERNS3_I NS0_17MySQL_DebugLoggerEEE+0x205)[0x7f821a98cde3]
/usr/lib/x86_64-linux-gnu/libmysqlcppconn.so.7(_ZN3sql5mysql15MySQL_Statement12e xecuteQueryERKNS_9SQLStringE+0x11b)[0x7f821a99443f]
./server(+0x326e)[0x56192448126e]
./server(+0x2f40)[0x561924480f40]
./server(+0x2da3)[0x561924480da3]
./server(+0x2a45)[0x561924480a45]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x76ca)[0x7f8219dfc6ca]
/lib/x86_64-linux-gnu/libc.so.6(clone+0x5f)[0x7f8219b360af]
class and the constructor:
class dataProcess : public thread
{
public:
dataProcess(int sock);
virtual ~dataProcess();
protected:
virtual void thread_handler();
private:
void wrongPass();
void loginProcess(byte* packet, uint16_t length);
void sendPacket(string packet);
int sock;
player* p;
Driver* driver;
unique_ptr<Connection> con;
};
dataProcess::dataProcess(int sock)
{
this->sock = sock;
driver = get_driver_instance();
con.reset(driver->connect("localhost", "root", "password"));
con->setSchema("ts_server");
thread::startThread();
}

Ok guys I have solved this problem and I have learned a very important lesson as a newbie. The problem occurs due to the undefined behaviour caused by my carelessness to ensure I have "deleted all my dynamically allocated variables" Once I have added delete in the right place everything works perfectly. so anyone facing these kind of random problems make sure to check these :)

Related

std::list::empty() returns true even though list is filled

I am having issues in a code having structure similar to the following minimum example. There is only one instance of MainClass. It makes new instance of Classlet on each call to its MainClass::makeclasslet()
I have multiple classlets writing to a single list buffer. After some time I need to copy/ dump the values from list buffer (FIFO).
The problem is that I am getting the following output in MainClass::clearbuffer()
>>>>>>>>>> 704 >>>>>>>>>>>>>>>>>>> Buffer size: 65363..... 1
I am unable to understand why the std::list::empty() returns true even when the buffer is locked with an atomic bool flag.
I have tried moving the call to clearbuffer() (in addval()) to the main application thread so that not each Classlet event calls clearbuffer().
I have also tried adding delay QThread::msleep(10); after setting busy = true;.
But some time after the application starts, I am getting the output shown above. Instead of popping all 65363+704 values in the list, it only popped 704 and broke the loop on list::isempty() being true (apparently).
class MainClass : public QObject {
Q_OBJECT
private:
std:: list<int> alist;
std::atomic<bool> busy;
MainClass() {
busy = false;
}
~MainClass() {
// delete all classlets
}
void makeclasslet() {
Classlet newclasslet = new Classlet();
// store the reference
}
void addval(int val) {
alist.push_back(val);
if (alist.size() > 100)
{
if (!busy)
{
clearbuffer();
}
}
}
void clearbuffer() {
if (!busy)
{
busy = true;
int i = 0;
while (!alist.empty())
{
i = i + 1;
// save alist.front() to file
alist.pop_front();
}
printf(">>>>>>>>>> %d >>>>>>>>>>> Buffer size: %d ..... %d\n", i, m_lstCSVBuffer.size(), m_lstCSVBuffer.empty());
busy = false;
}
}
}
class Classlet {
private:
Mainclass* parent;
void onsomeevent(int val) {
parent->addval(val);
}
}
I am using qt5.9 on Ubuntu 18.04. GCC/ G++ 7.5.0

Memory usage of C++ program grows, (shown in Debian's "top"), until it crashes

I'm working on a C++ program that should be able to run for several days, so it is a bit of a hassle that its memory consumption seems to grow really fast.
The full code of the program is a little long, so I'll post just the related things. The structure is the following:
int main (void){
//initialization of the global variables
error = 0;
state = 0;
cycle = 0;
exportcycle = 0;
status = 0;
counter_temp_ctrl = 0;
start = 0;
stop = 0;
inittimer();
mysql_del ("TempMeas");
mysql_del ("TempMeasHist");
mysql_del ("MyControl");
mysql_del ("MyStatus");
initmysql();
while(1){
statemachine();
pause();
}
}
The timer function that is initialized above is the following:
void catch_alarm (int sig)
{
//Set the statemachine to state 1 (reading in new values)
start = readmysql("MyStatus", "Start", 0);
stop = readmysql("MyStatus", "Stop", 0);
if (start == 1){
state = 1;
}
if (stop == 1){
state = 5;
}
//printf("Alarm event\n");
signal (sig, catch_alarm);
return void();
}
So basically, since I'm not setting the start bit in the webinterface that modifies the MyStatus Tab the program just calls the readmysql function twice every second (the timer's interval). The readmysql function is given below:
float readmysql(string table, string row, int lastvalue){
float readdata = 0;
// Initialize a connection to MySQL
MYSQL_RES *mysql_res;
MYSQL_ROW mysqlrow;
MYSQL *con = mysql_init(NULL);
if(con == NULL)
{
error_exit(con);
}
if (mysql_real_connect(con, "localhost", "user1", "user1", "TempDB", 0, NULL, 0) == NULL)
{
error_exit(con);
}
if (lastvalue == 1){
string qu = "Select "+ row +" from "+ table +" AS a where MeasTime=(select MAX(MeasTime) from "+ table;
error = mysql_query(con, qu.c_str());
}
else{
string qu = "Select "+ row +" from "+ table;
error = mysql_query(con, qu.c_str());
}
mysql_res = mysql_store_result(con);
while((mysqlrow = mysql_fetch_row(mysql_res)) != NULL)
{
readdata = atoi(mysqlrow[0]);
}
//cout << "readdata "+table+ " "+row+" = " << readdata << endl;
// Close the MySQL connection
mysql_close(con);
//delete mysql_res;
//delete mysqlrow;
return readdata;
}
I thought that the variables in this function are stored on the stack and are freed automaticaly when leaving the function. However it seems that some part of the memory is not freed, because it just grows after all. As you can see I have tried to use the delete function on two of the variables. Seems to have no effect. What am i doing wrong in terms of memory-management and so on?
Thanks for your help!
Greetings Oliver.
At least mysql_store_result is leaking. From documentation:
After invoking mysql_query() or mysql_real_query(), you must call mysql_store_result() or mysql_use_result() for every statement that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN, CHECK TABLE, and so forth). You must also call mysql_free_result() after you are done with the result set.
If your program continuously consumes memory (without ever releasing it), then you have a memory leak.
A good way to detect memory leaks, is to run it through a memory debugger, e.g. valgrind:
$ valgrind /path/to/my/program
Once your program started eating memory, stop it and valgrind will give you a nice summary about where your program allocated memory that was never freed.
There is no need to let the system run out of memory and crash; just wait until it has eaten some memory that has not been freed. Then fix your code. Then repeat until no more memory errors can be detected.
Also note that valgrind intercepts your systems memory management. This usually results in a (severe) performance penalty.

Segmentation fault(core dumped) in multi threading using boost threads

When try to run my program with up to 1 thread, it works fine for a while (some seconds or minutes) but finally get segmentation fault(core dumped) or double free(faststop ) error.
Here are the function which the threads run.
//used in the Function
[Added] typedef folly::ProducerConsumerQueue<std::string*> PcapTask;
struct s_EntryItem {
Columns* p_packet; //has some arbitrary method and variables
boost::mutex _mtx;
};
//_buffersConnection.wait_and_pop()
Data wait_and_pop() {
boost::mutex::scoped_lock lock(the_mutex);
while (the_queue.empty()) {
the_condition_variable.wait(lock);
}
Data popped_value = the_queue.front();
the_queue.pop();
return popped_value;
}
struct HandlerTask {
std::string year;
folly::ProducerConsumerQueue<std::string*> queue = NULL;
};
-----------------------------------------
//The function which threads run
void Connection() {
std::string datetime, year;
uint32_t srcIPNAT_num, srcIP_num;
std::string srcIP_str, srcIPNAT_str, srcIPNAT_str_hex;
int counter = 0;
while (true) {
//get new task
HandlerTask* handlerTask = _buffersConnection.wait_and_pop();
PcapTask* pcapTask = handlerTask->queue;
year = handlerTask->year;
counter = 0;
do {
pcapTask->popFront();
s_EntryItem* entryItem = searchIPTable(srcIP_num);
entryItem->_mtx.lock();
if (entryItem->p_packet == NULL) {
Columns* newColumn = new Columns();
newColumn->initConnection(srcIPNAT_str, srcIP_str, datetime, srcIP_num);
entryItem->p_packet = newColumn;
addToSequanceList(newColumn);
} else {
bool added = entryItem->p_packet->addPublicAddress(srcIPNAT_str_hex, datetime);
if (added == false) {
removeFromSequanceList(entryItem->p_packet);
_bufferManager->addTask(entryItem->p_packet);
Columns* newColumn = new Columns();
newColumn->initConnection(srcIPNAT_str, srcIP_str, datetime, srcIP_num);
//add to ip table
entryItem->p_packet = newColumn;
addToSequanceList(newColumn);
}
}
entryItem->_mtx.unlock();
++_totalConnectionReceived;
} while (true);
delete pcapTask;
delete handlerTask;
}
}
You can use Valgrind, its very easy. Build your app in debug config and pass program executable to valgrind. It can tell you wide spectre of programming errors occuring in your app in runtime. The price of using Valgrind is that program runs considerably slower (some times tens times slower) than without Valgrind. Specically, for example, Valgrind will tell you where your your programs' memory was free'ed first when it tried to free it second time when it happens.
I'm not sure that it's the problem, but...
Are you sure that you must call delete over pcapTask?
I mean: you delete it but queue in struct HandlerTask is a class member, not a pointer to a class.
Suggestion: try to comment the line
delete pcapTask;
at the end of Connection()
--- EDIT ---
Looking at you added typedef, I confirm that (if I'm not wrong) there is something strange in your code.
pcapTask is defined as a PcapTask pointer, that is a folly::ProducerConsumerQueue<std::string*> pointer; you initialize it with a folly::ProducerConsumerQueue<std::string*> (not pointer)
I'm surprised that you can compile your code.
I think you should, first of all, resolve this antinomy.
p.s.: sorry for my bad English.

How to handle and avoid Recursions

I'm using custom classes to manage a vending machine. I can't figure out why it keeps throwing a stack overflow error. There are two versions to my program, the first is a basic test to see whether the classes etc work, by pre-defining certain variables. The second version is what it should be like, where the variables in question can change each time the program is ran (depending on user input).
If anyone can suggest ways of avoiding this recursion, or stack overflow, I'd great. Below is the code for the three classes involved;
class Filling
{
protected:
vector<Filling*> selection;
string fillingChosen;
public:
virtual float cost()
{
return 0;
}
virtual ~Filling(void)
{
//needs to be virtual in order to ensure Condiment destructor is called via Beverage pointer
}
};
class CondimentDecorator : public Filling
{
public:
Filling* filling;
void addToPancake(Filling* customerFilling)
{
filling = customerFilling;
}
~CondimentDecorator(void)
{
delete filling;
}
};
class Frosted : public CondimentDecorator
{
float cost()
{ //ERROR IS HERE//
return (.3 + filling->cost());
}
};
Below is the code used to call the above 'cost' function;
void displayCost(Filling* selectedFilling)
{
cout << selectedFilling->cost() << endl;
}
Below is part of the code that initiates it all (main method);
Filling* currentPancake = NULL;
bool invalid = true;
do
{
int selection = makeSelectionScreen(money, currentStock, thisState);
invalid = false;
if (selection == 1)
{
currentPancake = new ChocolateFilling;
}
else if...
.
.
.
.
else
invalid = true;
} while (invalid);
bool makingSelection = true;
CondimentDecorator* currentCondiment = NULL;
do
{
int coatingSelection = makeCoatingSelectionScreen(money, currentStock, thisState);
if (coatingSelection == 1)
currentCondiment = new Frosted;
else if (coatingSelection == 2)...
.
.
.
else if (coatingSelection == 0)
makingSelection = false;
currentCondiment = thisSelection;
currentCondiment->addToPancake(currentPancake);
currentPancake = currentCondiment;
displayCost(currentPancake);
//Below is the code that DOES work, however it is merely meant to be a test. The
//above code is what is needed to work, however keeps causing stack overflows
//and I'm uncertain as to why one version works fine and the other doesn't
/*currentCondiment = new Frosted;
currentCondiment->addToPancake(currentPancake);
currentPancake = currentCondiment;
displayCost(currentPancake);
currentCondiment = new Wildlicious;
currentCondiment->addToPancake(currentPancake);
currentPancake = currentCondiment;
displayCost(currentPancake);*/
} while (makingSelection);
displayCost(currentPancake);
delete currentPancake;
The infinite recursion happens when you call displayCostwith a Frosted whose filling is a Frosted as well. And that happens right here:
currentCondiment->addToPancake(currentPancake);
currentPancake = currentCondiment;
displayCost(currentPancake);
You set the filling of currentCondiment to currentPancake, then call displayCost with currentCondiment.
In the process you also leak the memory that was originally assigned to currentPancake.
Btw currentCondiment = thisSelection; also leaks memory.
Idea: Use smart pointers like std::unique_ptr to get rid of the leaks.

Threads C++, Access Violation reading location x error

Platform : Windows 7
I'm developing a project for known text cipher attack in which;
Main process creates n child processes
Child processes decrypt an encrypted string, key subspace is partitioned according to number of child processes
Communication between child processes are by a static variable
for(int i = 0; i<info.totalNumberOfChildren; i++)
{
startChild( &info.childInfoList[i]);
//_beginthread(startChild, 0, &info.childInfoList[i]);
}
Above code works fine since:
First child starts execution, the key is set as a number such as 8 for testing purposes which is within the first child's partition, so first child finds the key, reports and sets true the killSwitch.
All the other children that are created are closed even before checking the first key as the killSwitch is true.
When I however do this :
for(int i = 0; i<info.totalNumberOfChildren; i++)
{
//startChild( &info.childInfoList[i]);
_beginthread(startChild, 0, &info.childInfoList[i]);
}
I get an access violation error. What could possibly be my source of error ?
Edit: I will try to share as relevant code as I can
startChild does the following:
void startChild( void* pParams)
{
ChildInfo *ci = (ChildInfo*)pParams;
// cout<<"buraya geldi"<<endl;
ChildProcess cp(*ci);
// write to log
cp.completeNextJob();
}
childInfo holds the following :
// header file
class ChildInfo
{
public:
ChildInfo();
ChildInfo(char * encrypted, char * original, static bool killSwitch, int totalNumOfChildren, int idNum, int orjLen);
void getNextJob();
bool keyIsFound();
Des des;
void printTest();
bool stopExecution;
bool allIsChecked;
char * encyptedString;
char * originalString;
int id;
int orjStrLen;
private:
int lastJobCompleted;
int totalNumberOfChildren;
int jobDistBits;
};
completeNextJob() does the following :
void ChildProcess::completeNextJob()
{
cout<<"Child Id : "<<info.id<<endl;
// cout<<"Trying : "<<info.encyptedString<<endl; // here I got an error
char * newtrial = info.encyptedString;
char * cand = info.des.Decrypt(newtrial); // here I also get an error if I comment out
/*
cout<<"Resultant : "<<cand<<endl;
cout<<"Comparing with : "<<info.originalString<<endl;
*/
bool match = true;
for(int i = 0; i<info.orjStrLen; i++)
{
if(!(cand[i] == info.originalString[i]))
match = false;
}
if(match)
{
cout<<"It has been acknowledged "<<endl;
info.stopExecution = true;
return;
}
else
{
if(!info.keyIsFound())
{
if(!info.allIsChecked)
{
info.getNextJob();
completeNextJob();
}
else
{
}
}
else
{
}
}
}
decrypt() method does the following :
char * Des::Decrypt(char *Text1)
{
int i,a1,j,nB,m,iB,k,K,B[8],n,t,d,round;
char *Text=new char[1000];
unsigned char ch;
strcpy(Text,Text1); // this is where I get the error
i=strlen(Text);
keygen();
int mc=0;
for(iB=0,nB=0,m=0;m<(strlen(Text)/8);m++) //Repeat for TextLenth/8 times.
{
for(iB=0,i=0;i<8;i++,nB++)
{
ch=Text[nB];
n=(int)ch;//(int)Text[nB];
for(K=7;n>=1;K--)
{
B[K]=n%2; //Converting 8-Bytes to 64-bit Binary Format
n/=2;
} for(;K>=0;K--) B[K]=0;
for(K=0;K<8;K++,iB++) total[iB]=B[K]; //Now `total' contains the 64-Bit binary format of 8-Bytes
}
IP(); //Performing initial permutation on `total[64]'
for(i=0;i<64;i++) total[i]=ip[i]; //Store values of ip[64] into total[64]
for(i=0;i<32;i++) left[i]=total[i]; // +--> left[32]
// total[64]--|
for(;i<64;i++) right[i-32]=total[i];// +--> right[32]
for(round=1;round<=16;round++)
{
Expansion(); //Performing expansion on `right[32]' to get `expansion[48]'
xor_oneD(round);
substitution();//Perform substitution on xor1[48] to get sub[32]
permutation(); //Performing Permutation on sub[32] to get p[32]
xor_two(); //Performing XOR operation on left[32],p[32] to get xor2[32]
for(i=0;i<32;i++) left[i]=right[i]; //Dumping right[32] into left[32]
for(i=0;i<32;i++) right[i]=xor2[i]; //Dumping xor2[32] into right[32]
} //rounds end here
for(i=0;i<32;i++) temp[i]=right[i]; // Dumping -->[ swap32bit ]
for(;i<64;i++) temp[i]=left[i-32]; // left[32],right[32] into temp[64]
inverse(); //Inversing the bits of temp[64] to get inv[8][8]
/* Obtaining the Cypher-Text into final[1000]*/
k=128; d=0;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
d=d+inv[i][j]*k;
k=k/2;
}
final[mc++]=(char)d;
k=128; d=0;
}
} //for loop ends here
final[mc]='\0';
char *final1=new char[1000];
for(i=0,j=strlen(Text);i<strlen(Text);i++,j++)
final1[i]=final[j]; final1[i]='\0';
return(final);
}
Windows is trying to tell you why your program crashed. Please use a debugger to see what Windows is talking about. Location X is important: it should tell you whether your program is dereferencing NULL, overflowing a buffer, or doing something else. The call stack at the time of the crash is also very important.
Debugger is your best friend, try to use it and check step by step what could cause this access violation.
I think that info.encyptedString is not initialized correctly and pointing to not allocated memory, but I cant be sure because you didn't show this part of code.
And of course you must protect your shared resources (info) using some synchronization objects like critical section or mutex or semaphore.
I don't know, the basic issue seems pretty straightforward to me. You have multiple threads executing simultaneously, which access the same information via *pParams, which presumably is of type ChildInfo since that's what you cast it to. That info must be getting accessed elsewhere in the program, perhaps in the main thread. This is corrupting something, which may or may not have to do with Text1 or info.id, these errors can often be 'non-local' and hard to debug for this reason. So start mutex-protecting the entire thread (within your initial loop), and then zero in on the critical sections by trial and error, i.e. mutex-protect as small a region of code as you can get away with without producing errors.