C++ Debug assertion failed, using Windows.h mutex - c++

I have a problem caused by this code:
char KernelFS::mount(Partition* part) {
WaitForSingleObject(mutexFS,INFINITE);
int pos;
for(pos=0; pos<26; pos++)
if(mountedPartitions[pos] == 0)
break;
if(pos < 26) {
mountedPartitions[pos] = part;
bitVectors[pos] = new BitVector(part);
fileEvidention[pos] = new ListHandler();
openedFiles[pos] = 0;
forbidOpening[pos] = false;
ReleaseMutex(mutexFS);
return intToChar(pos);
}
else {
ReleaseMutex(mutexFS);
return '0';
}
}
and
char KernelFS::format(char part){
WaitForSingleObject(mutexFS,INFINITE);
forbidOpening[charToInt(part)] = true;
ReleaseMutex(mutexFS);
while(openedFiles[charToInt(part)]>0)
WaitForSingleObject(unmountSem,INFINITE);
WaitForSingleObject(mutexFS,INFINITE);
// write fresh bit vector to cluster 0 of partition
bitVectors[charToInt(part)]->formatBitVector();
openedFiles[charToInt(part)] = 0;
forbidOpening[charToInt(part)] = false;
delete fileEvidention; //!!***!!
fileEvidention[charToInt(part)] = new ListHandler();
// some other stuff, irrelevant
ReleaseMutex(mutexFS);
return 1;
}
There are 3 thread executing, 1 is blocked and two are running through this code;
they first call mount, then format (each has its own argument Partition object, p1 and p2).
The first time mount is called, it always goes through - then there is an assertion failure at random during one of the next calls of mount/format by any of the two running threads.
Usually, it fails during thread 1 - it calls mount(..) completes it, then calls format(...) and fails around:
delete fileEvidention[charToInt(pos)];
(in debug mode, when I reach this instruction, even if I try to go into with F11, there is an assertion failure)
In case it matters... this is the initialization:
char KernelFS::firstLetter = 'A'; // 'A' = 65
Partition* KernelFS::mountedPartitions[26] = {0}; // init. no partitions are mounted
BitVector* KernelFS::bitVectors[26] = {0}; // init. no partitions are mounted
bool KernelFS::forbidOpening[26] = {false};
long KernelFS::openedFiles[26] = {0};
ListHandler* KernelFS::fileEvidention[26] = {0};
HANDLE KernelFS::mutexFS = CreateMutex(0,0,0);
HANDLE KernelFS::unmountSem = CreateSemaphore(0,0,INFINITE,0);
I have never had this error before, I have no idea how to debug this nor what could cause it.
Thanks for the help, in advance.
EDIT:
when i remove the marked line of code (and ignore the memory leak) there is no assertion failure. What is this witchcraft ?
! :)

Solved. should be
delete fileEvidention[charToInt(part)];
......

Related

Simulating Leach has encounter a problem. Finished with error in omnet++

When running the simulation in omnet++ 5.7 the execution stops suddenly and closes.
This is the code that is being run in omnet
auto simulation = getSimulation();
for (i = 1; i <= simulation->getLastComponentId(); i++) {
int x, y, id;
//scan the simulation module vector
mod = (cModule*)simulation->getModule(i);
if (strcmp(mod->getName(), "node") == 0) {
id = ((Node*)mod)->myId;
x = ((Node*)mod)->xpos;
y = ((Node*)mod)->ypos;
nodePtr[id] = ((Node*)mod);
if (id != this->myId) {
cGate* g;
char gName1[32], gName2[32];
// make new gate here
if (this->hasGate(gName1)) {
this->gate(gName1)->disconnect();
this->deleteGate(gName1);
}
this->addGate(gName1, cGate::OUTPUT, false);
// make new gate at other side
if (mod->hasGate(gName2)) {
mod->gate(gName2)->disconnect();
mod->deleteGate(gName2);
}
mod->addGate(gName2, omnetpp::cGate::INPUT, false);
//CHANNEL
cIdealChannel* ch = NULL;
this->gate(gName1)->connectTo(mod->gate(gName2), ch);
g = this->gate(gName1);
g->setDisplayString(g->getDisplayString());
}
}
}
I assume that the last line g->setDisplayString(g->getDisplayString()); is probably where the code breaks. The code repeats in the for loop with i<= simulation->getLastComponentId(). I'm new to Omnet++. Any suggestion to fix this would be helpful.
Thanks.
Several things in your code may be source of crashing:
getModule(i) may return nullptr, see OMNeT++ Simulation API, so you should check in the code whether result is not nullptr.
gName1 and gName2 are not set!
Other issues:
instead of (Node*)mod use dynamic_cast<Node*)>(mod) and check whether results is not nullptr.
instead of strcmp(mod->getName(), "node") == 0 I advice using mod->isName("node") - see OMNeT++ Simulation API
if you want to obtain a module whose name is "node", you do not need to manually check the name of every module - there is a useful method getModuleByPath() see OMNeT++ Simulation Manual

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.

Creating new objects in C++ function causes program to crash

I have a program which allows the user to play Dominoes against 3 CPU players, with varying difficulty. Each CPU player can be either Beginner, Intermediate or Expert, and each difficulty has it's own class. If I initiate my 3 CPU players at the beginning of my 'Window' class (below), the program runs fine.
In Window.h
public:
Window(QWidget *parent = 0);
Intermediate *cpu1;
Beginner *cpu2;
Intermediate *cpu3;
In Window.cpp
Window::Window(QWidget *parent):QDialog(parent) {
cpu1 = new Intermediate;
cpu2 = new Beginner;
cpu3 = new Intermediate;
}
However I want the user to be able to select the CPU difficulties at the beginning of the game, so I now have a function within 'Window' that creates the objects. As soon as I call this function the game freezes and I get an error message pop up saying telling me the program has ended unexpectedly.
void Window:: startGame(){
cpu1 = new Intermediate;
cpu2 = new Beginner;
cpu3 = new Intermediate;
}
If anyone would be able to explain to me what is going on and what I can do to get around this that would be great.
Intermediate.cpp (Beginner.cpp is almost identical)
#include "intermediate.h"
Intermediate::Intermediate()
{
tilePlaced = false;
skipGo = false;
}
void Intermediate::findDoubles(int a[7][2]){
for(int i = 0; i < 7; i++){ // Creates new doubles list after each go.
doublesList[i] = 0;
}
for(int i = 0; i < 7; i++){ // Creates a list of doubles
if ((a[i][0] == a[i][1]) && (a[i][0] != 7)){
doublesList[a[i][0]] = 1;
}
}
}
bool Intermediate::addDomino(){} // Function that finds best domino to replace and returns bool
if(tilePlaced == false){
pass++;
text += "\nPassed turn";
return false;
}
else{
pass = 0;
text += QString("\nPlaced [%1 : %2]").arg(a).arg(b);
return true;
}
}
One way to start would be to narrow down which class is causing the fault. Does it work if they are all Beginner, or if they are all Intermediate? If so then the other one is causing the problem.

"printf" appears to be non-deterministic in Qt?

I know "printf" is standard-c and should be deterministic. But when run in Qt I see a more non-deterministic response(clock cycles). Could this be due to Qt adding some "pork" to its response?
I have multiple threads that make call to function that uses a mutex. When one thread enters it set a switch so the others can't until it is done. Things appeared to work ok for acouple seconds and then threads appeared to be killed off from 10 to 1 thread. So I tried adding a delay: (k=k+1: no help), then (looping k=k+1: no help), (usleep works), and so does (printf) work at creating a random delay and allowing all threads to continue running.
void CCB::Write(int iThread)
{
static bool bUse = false;
bool bDone = false;
char cStr[20];
int posWrite;// = *m_posWrite; // issue of posWrite be altered with next extrance
long k = 0;
long m = 0;
m_threadCount++;
while(bDone == false){
if(bUse == false){
bUse = true;
posWrite = *m_posWrite;
memcpy(m_cmMessageCB + posWrite, &m_cmMessageWrite, sizeof(typeCanMessage));
memset(cStr, '\0', 20);
memcpy(cStr, (m_cmMessageCB + posWrite)->cMessage, 11); //fails: every 20
*m_posWrite = *m_posWrite + 1;
if(*m_posWrite == m_iNBufferLength)
*m_posWrite = 0;
bDone = true;
bUse = false;
}else if(bUse == true){
//why are threads being killed ?
// printf("T%d_%d ", iThread, m_threadCount);//non-deterministic value ?
usleep(1);//non-deterministic value
//k++;//delay of a couple clock cycles was not enough
/*
for(k = 0; k < iThread * 100; k++){//deterministic and fails to resolve thread problem
m++;
}
*/
}
}
}

Dartium build error in Release mode

I was following http://code.google.com/p/dart/wiki/BuildingDartium#Build and attempted to build dartium in Release mode and encountered the following error:
$ ./dartium_tools/build.py --mode=Release
.
.
.
CXX(target) out/Release/obj.target/webrtc_video_coding/third_party/webrtc/modules/video_coding/main/source/rtt_filter.o
CXX(target) out/Release/obj.target/webrtc_video_coding/third_party/webrtc/modules/video_coding/main/source/session_info.o
CXX(target) out/Release/obj.target/webrtc_video_coding/third_party/webrtc/modules/video_coding/main/source/timestamp_extrapolator.o
third_party/webrtc/modules/video_coding/main/source/session_info.cc: In member function ‘int webrtc::VCMSessionInfo::PrepareForDecode(uint8_t*)’:
third_party/webrtc/modules/video_coding/main/source/session_info.cc:590:8: error: variable ‘previous_lost’ set but not used [-Werror=unused-but-set-variable]
cc1plus: all warnings being treated as errors
make: *** [out/Release/obj.target/webrtc_video_coding/third_party/webrtc/modules/video_coding/main/source/session_info.o] Error 1
make: *** Waiting for unfinished jobs....
Traceback (most recent call last):
File "./dartium_tools/build.py", line 67, in <module>
main()
File "./dartium_tools/build.py", line 64, in main
[target for (target, _) in targets])
File "/home/sangeeth/work/g/dartium/src/dartium_tools/utils.py", line 97, in runCommand
raise Exception('Failed to run command. return code=%s' % p.returncode)
Exception: Failed to run command. return code=2
$
But when I looked at the code dartium/src/third_party/webrtc/modules/video_coding/main/source/session_info.cc::VCMSessionInfo::PrepareForDecode(), I saw the following:
int VCMSessionInfo::PrepareForDecode(uint8_t* frame_buffer) {
int length = SessionLength();
int real_data_bytes = 0;
if (length == 0)
return length;
bool previous_lost = false;
PacketIterator it = packets_.begin();
PacketIterator prev_it = it;
for (; it != packets_.end(); ++it) {
bool packet_loss = ((*prev_it).sizeBytes == 0 ||
!InSequence(it, prev_it));
if ((*it).bits) {
if (prev_it != it) { // Not the first packet.
uint8_t* ptr_first_byte =
const_cast<uint8_t*>((*it).dataPtr);
if (packet_loss) {
// It is be better to throw away this packet if we are
// missing the previous packet.
memset(ptr_first_byte, 0, (*it).sizeBytes);
previous_lost = true;
++packets_not_decodable_;
} else if ((*it).sizeBytes > 0) {
// Glue with previous byte.
// Move everything from [this packet start + 1, end of buffer] one
// byte to the left.
uint8_t* ptr_prev_byte =
const_cast<uint8_t*>((*prev_it).dataPtr) +
(*prev_it).sizeBytes - 1;
*ptr_prev_byte = (*ptr_prev_byte) | (*ptr_first_byte);
memmove(const_cast<uint8_t*>((*it).dataPtr),
(*it).dataPtr + 1, (*it).sizeBytes - 1);
ShiftSubsequentPackets(it, -1);
(*it).sizeBytes--;
length--;
previous_lost = false;
real_data_bytes += (*it).sizeBytes;
}
} else {
memset(const_cast<uint8_t*>((*it).dataPtr), 0,
(*it).sizeBytes);
previous_lost = true;
++packets_not_decodable_;
}
} else if (packet_loss &&
(*it).codecSpecificHeader.codec == kRTPVideoH263) {
// Pad H.263 packet losses with 10 zeros to make it easier
// for the decoder.
const int kPaddingLength = 10;
WebRtc_UWord8 padding_data[kPaddingLength] = {0};
// Make a copy of the previous packet.
VCMPacket padding_packet(*it);
++padding_packet.seqNum;
padding_packet.dataPtr = padding_data;
padding_packet.sizeBytes = kPaddingLength;
length += InsertPacket(padding_packet, frame_buffer, false, 0);
previous_lost = true;
} else {
real_data_bytes += (*it).sizeBytes;
previous_lost = false;
}
prev_it = it;
}
if (real_data_bytes == 0) {
// Drop the frame since all it contains are zeros.
for (it = packets_.begin(); it != packets_.end(); ++it)
(*it).sizeBytes = 0;
length = 0;
}
return length;
}
The bool variable previous_lost has been used (set to false and true) at many places.
Any valuable input on how to go about this would be a great help.
Setting a bool to true or false is pointless if you don't then read the value later - in the code you posted, a value for previous_lost is indeed set in several places, but nowhere is the value that's set used to do anything (such as a if (previous_lost) ..., for example). That's what's meant by "used" in this context: a variable is used if its value is read.
Note that this (generally) applies for any type of variable: if I set an int to 42 and don't use it any later calculation, it's not "used" either.
In these cases, the variable is completely redundant - it does nothing useful since it is not used by other code. Generally this kind of warning is meant to indicate that perhaps the code that was supposed to use previous_lost was accidentally omitted (or was removed) and needs to be accounted for. Alternatively, the variable might simply be redundant and can be removed entirely.