Exception thrown with OpenCV's SVM training, c++ - c++

I have a problem with the Support Vector Machine , coding with visual studio, c++.
Tried to replicate the example of the tutorial at the following link
https://docs.opencv.org/3.4.0/d1/d73/tutorial_introduction_to_svm.html and the situation is
(having a breakpoint at "return 0;" line)
1) In debug , x64 I run the solution, and after "return 0" statement I have an exception thrown
at memory location (not unhandled, luckily) and then the program exit correctly.
2) In release, x64, I run the solution, and after "return 0" statement I have an exception thrown
at memory location but clicking on "continue" button, this appears (of mat.inl.hpp)
inline
void Mat::release()
{
if( u && CV_XADD(&u->refcount, -1) == 1 )
deallocate();
u = NULL;
datastart = dataend = datalimit = data = 0;
for(int i = 0; i < dims; i++)
----> size.p[i] = 0; <----- // (that's the exact line)!
#ifdef _DEBUG
flags = MAGIC_VAL;
dims = rows = cols = 0;
if(step.p != step.buf)
{
fastFree(step.p);
step.p = step.buf;
size.p = &rows;
}
#endif
}
And I have the correct exit of the program only clicking on "continue" bottom several times.
This happens only in release mode.
How to fix it?

Related

Get abending line number in C++ using Visual Studio

Okay, I've been beating my head against a brick wall for a couple of days now...
I have a __try __except piece of code with this in it:
__except(ExFilter(GetExceptionCode(),GetExceptionInformation())){
// Print the message ExFilter set up
MessageBox(NULL, (LPTSTR)outline, "setup/LoadSettingsFromIni error", MB_OK);
if(ExFilter_rc > 0) { // should we abend?
exit(9) ; // yes
}
} // end of __except...
and in the ExFilter code:
LONG ExFilter(DWORD error,LPEXCEPTION_POINTERS lpExceptionInfo){
void *addressPtr;
EXCEPTION_RECORD *myExecptionRecord;
myExecptionRecord = lpExceptionInfo->ExceptionRecord;
addressPtr = myExecptionRecord->ExceptionAddress;
At this point, addressPtr points to:
0x00007ff73b70d4c8 {Regshot-x64-ANSI-dbg.exe!LoadSettingsFromIni(HWND__ * hDlg), Line 355}
More of the code gets the program name using "GetModuleFileName" etc.
But I already know the program name.
I've tried many ways to get the data "Line 355" but no luck.
How do I get at it so I can put it in a message?
Thanks.
I'm sure many people have found a way around this, but here is my "poor man's solution" for trapping errors I suddenly thought of the other day:
I added a counter to areas in my code that might cause a problem, and then in the __except filter added code to show the counter, which would give me a more concise area to look at.
Here is what I did:
char outline[1310] ; // __except output line
size_t rc2 ; // lth of outline
int ctr ;
__try {
code
..
ctr = 1 ;
code
..
ctr = 2 ;
code
..
ctr = 3 ;
code
..
} // end of try
__except(ExFilter(GetExceptionCode(),GetExceptionInformation())){
// Print the message ExFilter set up
MessageBox(NULL, (LPTSTR)outline, "setup/LoadSettingsFromIni error", MB_OK);
if(ExFilter_rc > 0) { // should we abend?
exit(9) ; // yes
}
} // end of __except...
and in the ExFilter code:
LONG ExFilter(DWORD error,LPEXCEPTION_POINTERS
lpExceptionInfo){
void *addressPtr;
EXCEPTION_RECORD *myExecptionRecord;
myExecptionRecord = lpExceptionInfo->ExceptionRecord;
addressPtr = myExecptionRecord->ExceptionAddress;
sprintf(outline, ""); // blank outline
rc2 = strlen(outline);
rc = error ; // GetExceptionCode() passed by __except
if (rc == EXCEPTION_INT_DIVIDE_BY_ZERO) {
sprintf(outline+rc2, "Divide by Zero!");
goto f_end7a ; // continue
}
... more code for each trapped error.....
f_end7a: ;
rc2 = strlen(outline);
sprintf(outline+rc2, "\n\nError occured after instruction \"ctr = %i ;\" \n", ctr);
return EXCEPTION_EXECUTE_HANDLER; // return to __except...
So if an error occurs, a message is displayed, with a line like:
Error occurred after instruction "ctr = 2"
and I know approximately where it happened, between ctr = 2 and ctr = 3.
This may be "Mickey Mouse", but it's better than nothing.

Why do I get this C++ error (terminate called after throwing an instance of 'std::bad_alloc') when I am playing the code?

I wrote the code pasted below to perform a method that starts monotrack and generates tracks.
void KalmanTracker::TrackInitiation(AssignData *track_, vector<int> *CT_order_, Camera *cam)
{
vector<int> CT_order= *CT_order_;
Functions f;
double T,X_MAX,X_MIN,Y_MAX,Y_MIN;
int numtracks = 0;
for(int curr_p=0; curr_p<track_->num_DTBP; curr_p++) { //plot in the current frame
if(track_->Data_TBP.at(curr_p).Free == false) {
for(int ant_p=0; ant_p<track_->num_DANT; ant_p++) { //plot in the previous frame
T = track_->Data_TBP.at(curr_p).Dato.t_obt - track_->Data_ANT.at(ant_p).Dato.t_obt;
X_MAX = track_->Data_ANT.at(ant_p).Dato.Est_PosXY.at(Xx) + MAX_SPEED*T + 3.0*sqrt(2.0*RX);
X_MIN = track_->Data_ANT.at(ant_p).Dato.Est_PosXY.at(Xx) - MAX_SPEED*T - 3.0*sqrt(2.0*RX);
Y_MAX = track_->Data_ANT.at(ant_p).Dato.Est_PosXY.at(Yy) + MAX_SPEED*T + 3.0*sqrt(2.0*RY);
Y_MIN = track_->Data_ANT.at(ant_p).Dato.Est_PosXY.at(Yy) - MAX_SPEED*T - 3.0*sqrt(2.0*RY);
if((track_->Data_TBP.at(curr_p).Dato.Est_PosXY.at(Xx) < X_MAX) && (track_->Data_TBP.at(curr_p).Dato.Est_PosXY.at(Xx) > X_MIN) &&
(track_->Data_TBP.at(curr_p).Dato.Est_PosXY.at(Yy) < Y_MAX) && (track_->Data_TBP.at(curr_p).Dato.Est_PosXY.at(Yy) > Y_MIN)) {
if((track_->Data_TBP.at(curr_p).Dato.Area > 10) && (track_->Data_ANT.at(ant_p).Dato.Area > 10) &&
(track_->Data_TBP.at(curr_p).Dato.InBox == false) && (track_->Data_ANT.at(ant_p).Dato.InBox == false)) {
f.InitiateMonotrack(track_,track_->Data_ANT.at(ant_p).Dato,track_->Data_TBP.at(curr_p).Dato,&CT_order,numtracks); //Start the monotrack
numtracks++;
track_->Data_TBP.at(curr_p).Free = true;
}
}
}
}
}
// Reordering and saving CT_order
int num_non_discarded = 0;
for(int i=0; i<track_->num_CT+numtracks; i++) {
if (CT_order.at(i) != -1) {
CT_order.at(num_non_discarded) = CT_order.at(i);
num_non_discarded++;
}
}
track_->num_CT = min(num_non_discarded,MAX_CT-1);
// Copy CT_order to the CT_order of the track
for(int i=0; i<track_->num_CT; i++)
track_->CT_order.at(i) = CT_order.at(i);
// Releasing previous plots
int num_ANT = 0;
for(int i=0; i<track_->num_DANT; i++)
track_->Data_ANT.at(i).Free = true;
// Copy the current plot to previous plot
for(int curr_p=0; curr_p<track_->num_DTBP; curr_p++) {
if (track_->Data_TBP.at(curr_p).Free == false) {
track_->Data_ANT.at(num_ANT).Dato.t_obt = track_->Data_TBP.at(curr_p).Dato.t_obt;
track_->Data_ANT.at(num_ANT).Dato.Est_PosXY.resize(2);
track_->Data_ANT.at(num_ANT).Dato.Est_PosXY.at(Xx) = track_->Data_TBP.at(curr_p).Dato.Est_PosXY.at(Xx);
track_->Data_ANT.at(num_ANT).Dato.Est_PosXY.at(Yy) = track_->Data_TBP.at(curr_p).Dato.Est_PosXY.at(Yy);
track_->Data_ANT.at(num_ANT).Dato.Area = track_->Data_TBP.at(curr_p).Dato.Area;
track_->Data_ANT.at(num_ANT).Dato.InBox = track_->Data_TBP.at(curr_p).Dato.InBox;
track_->Data_TBP.at(curr_p).Dato.image.copyTo(track_->Data_ANT.at(num_ANT).Dato.image);
track_->Data_ANT.at(num_ANT).Free = false;
num_ANT++;
}
}
track_->num_DANT = min(num_ANT,MAX_DTBP-1);
// Releasing current plots
for(int curr_p=0; curr_p<track_->num_DTBP; curr_p++)
track_->Data_TBP.at(curr_p).Free = true;
track_->num_DTBP = 0;
*CT_order_= CT_order;
}
When I execute the .cpp file I keep getting the error message:
terminate called after throwing an instance of 'std::bad_alloc'
terminate called recursively
what(): std::bad_alloc
I have gathered this has to do with a memory shortage or variables falling out of the main() function, but I can not figure out how to address the problem in this specific situation. If it is relevant, I am working on a Linux computer, programming in eclipse, using C++ language and opencv and boost libraries, because my project has two threads.
[EDIT] The debugger tells me:
Can't find a source file at "/build/glibc-t3gR2i/glibc-2.23/signal/../sysdeps/unix/sysv/‌​linux/raise.c" Locate the file or edit the source lookup path to include its location.
And the source not found is __GI_raise() at raise.c.
And after that error, the console tells me:
[xcb] Unknown sequence number while processing reply
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that. dronesNuevo: ../../src/xcb_io.c:635: _XReply: Assertion `!xcb_xlib_threads_sequence_lost' failed.
But other times the debugger tells me:
Thread 3 received signal SIGSEGV, Segmentation fault.
[Cambiando a Thread 0x7fffe1f69700 (LWP 17536)] 1574 ../sysdeps/x86_64/multiarch/memcpy-ssse3-back.S: No existe el archivo o el directorio.
__memmove_ssse3_back () at ../sysdeps/x86_64/multiarch/memcpy-ssse3-back.S:1574
and:
Can't find a source file at "/build/glibc-t3gR2i/glibc-2.23/string/../sysdeps/x86_64/mul‌​tiarch/memcpy-ssse3-‌​back.S"
Locate the file or edit the source lookup path to include its location.
Being the source not found __memmove_ssse3_back() at memcpy-sse3-back.S
The backtrace that I get:
*** Error in `path': double free or corruption (!prev): 0x00007fffa007ecb0 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7ffff5e577e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x7fe0a)[0x7ffff5e5fe0a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7ffff5e6398c]
path[0x40d3b6]
path[0x40cc26]
path[0x40bd78]
path[0x40b3a2]
path[0x409f3f]
path[0x40813b]
path[0x412bd7]
path[0x43df93]
path[0x44826b]
path[0x447f38]
path[0x447ac2]
/usr/lib/x86_64-linux-gnu/libboost_thread.so.1.58.0(+0x115d5)[0x7ffff6a5b5d5]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x76ba)[0x7ffff59b06ba]
/lib/x86_64-linux-gnu/libc.so.6(clone+0x6d)[0x7ffff5ee682d]

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

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)];
......

unhandled exception Access violation writing location in Visual Studio

Is there a way in Visual Studio 2005 to find out which pointer or variable is causing this access violation? I tried to run in debug mode and break when it happens. By looking at the call stacks, it happens in the end of the function (see below). Could using try/catch be able to find out which pointer it is?
EDIT:
Posting my code:
There is a Qt line edit and a checkbox in my application. Toggling the checkbox would switch the data format in the line edit. Like 3'b111 <==> 3'h7. Below is the callback function that is connected to the checkbox stateChanged signal. The exception happens in the end of function, when destructing local variables.
// switch hex/binary format. 15'h0000 <==> 15'b000000000000000
void switchDataFormat(int checkState) {
QLineEdit* writeRegLE = this->getWriteRegLineEdit();
string oldText = writeRegLE->text().toStdString();
string newText = "";
int maxLength;
string regLengthText = oldText.substr(0, oldText.find('\''));
string regValueText = oldText.substr(oldText.find('\'')+2);
int regLength = this->getRegLength();
if (checkState == Qt::Unchecked) {
// switch to binary format
maxLength = regLengthText.size() + 2 + regLength;
string binaryText;
for (int i = 0; i < regValueText.size(); ++i) {
binaryText += hexToBinary(regValueText[i]);
}
newText = regLengthText + "'b" + binaryText.substr(binaryText.size()-regLength); // trimming leading zeros to fit regLength
}
else {
// switch to hex format
maxLength = regLengthText.size() + 2 + regLength/4 + 1;
newText = regLengthText + "'h";
// zero filling to 4*n bits
if (regLength%4 != 0) regValueText = string(regLength%4,'0') + regValueText;
for (int i = 0; i < regValueText.size(); i+=4) {
newText += binaryToHex(regValueText.substr(i,4));
}
}
writeRegLE->setMaxLength(maxLength);
writeRegLE->setText(QString::fromUtf8(newText.c_str()));
}

Segmentation fault occurs only under release configuration

For some odd reason, my application likes to break on me when I switch to release and run it outside of my debugger. Here's what works for me, and here's what doesn't
(Qt Creator is the IDE)
Debugging with debug configuration - ok
Running with debug configuration - ok
Debugging with release configuration - ok
Running with release configuration - application crash
My UI is one project, and the core for some stuff as a separate dependency. On Windows (compiling with MSVCC), I hit a menu button, which eventually calls down to a function. In that function, the app breaks on adding a new element to a vector. e.g:
str *x = new str();
str *y = new str();
/* ...set some of x & y's members... */
vector.push_back(x); // works fine
vector.push_back(y); // causes crash
If I comment out the line vector.push_back(y);, the app continues no problem until the app leaves the event scope (i.e. the end of OnMenuButtonClick). On OS X, it's similar to the issue of adding an element to a vector, except I have:
std::vector<foo *> SomeFunction()
{
std::vector<foo *> returningVector;
/* do stuff */
std::vector<foo *> goo = GetFooObjects();
for (int i = 0; i < goo.size(); i++)
{
returningVector.push_back(goo[i]); // breaks here
}
}
So what are some causes of this strange behavior without a debugger attached and not under debug configuration? I've checked to make sure all of my variables are initialized, so I'm stumped. If you want to view the code above, the first part can be located here, and the second part here. Please forgive anything you see as "bad", and if you have suggestions that you just can't contain, then please do message me on GitHub.
Edit:
I looked more into it, and found out exactly what's causing the problem, but don't know how to fix it. This is the function where my app crashes (on OS X):
vector<Drive *> Drive::GetFATXDrives( bool HardDisks )
{
vector<Drive *> Return;
if (HardDisks)
{
vector<DISK_DRIVE_INFORMATION> Disks = GetPhysicalDisks();
for (int i = 0; i < (int)Disks.size(); i++)
{
DISK_DRIVE_INFORMATION ddi = Disks.at(i);
// First, try reading the disk way
Streams::xDeviceStream* DS = NULL;
try
{
char path[0x200] = {0};
wcstombs(path, ddi.Path, wcslen(ddi.Path));
DS = new Streams::xDeviceStream(ddi.Path);
}
catch (xException& e)
{
continue;
}
if (DS == NULL || DS->Length() == 0 || DS->Length() < HddOffsets::Data)
{
// Disk is not of valid length
continue;
}
DS->SetPosition(HddOffsets::Data);
// Read the FATX partition magic
int Magic = DS->ReadInt32();
// Close the stream
DS->Close();
// Compare the magic we read to the *actual* FATX magic
if (Magic == FatxMagic)
{
Drive *d = new Drive(Disks.at(i).Path, Disks.at(i).FriendlyName, false);
Return.push_back(d);
}
}
}
vector<Drive *> LogicalDisks = GetLogicalPartitions();
for (int i = 0; i < (int)LogicalDisks.size(); i++)
{
Return.push_back(LogicalDisks.at(i));
}
return Return;
}
If I change if (HardDisks) to if (HardDisks = false), the app works just fine. So, I looked into that scope and discovered that after vector<DISK_DRIVE_INFORMATION> Disks = GetPhysicalDisks();, the heap gets corrupt or something like that. I noticed this because in the debugger, after that function is called, my HardDisks bool changes to "false", which wasn't what it was before.
Here is GetPhysicalDisks:
vector<Drive::DISK_DRIVE_INFORMATION> Drive::GetPhysicalDisks( void )
{
// RIGHT AFTER this vector is initialized, everything goes to hell
vector<Drive::DISK_DRIVE_INFORMATION> ReturnVector;
DIR *dir;
dirent *ent;
dir = opendir("/dev/");
if (dir != NULL)
{
// Read the shit
while ((ent = readdir(dir)) != NULL)
{
// Check the directory name, and if it starts with "disk" then keep it!
QRegExp exp("disk*");
exp.setPatternSyntax(QRegExp::Wildcard);
exp.setCaseSensitivity(Qt::CaseInsensitive);
if (exp.exactMatch(ent->d_name))
{
DISK_DRIVE_INFORMATION curdir;
memset(curdir.FriendlyName, 0, sizeof(curdir.FriendlyName));
memset(curdir.Path, 0, sizeof(curdir.Path));
char diskPath[0x50] = {0};
sprintf(diskPath, "/dev/r%s", ent->d_name);
mbstowcs(curdir.Path, diskPath, strlen(diskPath));
int device;
if ((device = open(diskPath, O_RDONLY)) > 0)
{
#ifdef __linux
hd_driveid hd;
if (!ioctl(device, HDIO_GET_IDENTITY, &hd))
{
swprintf(curdir.FriendlyName, strlen(hd) * 2, L"%hs", hd.model);
}
#elif defined __APPLE__
mbstowcs(curdir.FriendlyName, ent->d_name, strlen(ent->d_name));
#endif
ReturnVector.push_back(curdir);
}
}
}
}
return ReturnVector;
}
While this isn't a real answer as to what happened, I did find a way to fix the problem. Looking at my edit above, I edited my Drive::GetFATXDrives function like so:
vector<Drive *> Drive::GetFATXDrives( bool HardDisks )
{
// Initialize Disks vector up here
vector<DISK_DRIVE_INFORMATION> Disks;
// Call the function to get the hard disks
if (HardDisks)
Drive::GetPhysicalDisks(Disks);
vector<Drive *> ReturnVector;
if (HardDisks)
{
Streams::xDeviceStream* DS = NULL;
for (int i = 0; i < (int)Disks.size(); i++)
{
/* ... */
}
if (DS)
{
DS->Close();
delete DS;
}
}
vector<Drive *> LogicalDisks = GetLogicalPartitions();
for (int i = 0; i < LogicalDisks.size(); i++)
{
ReturnVector.push_back(LogicalDisks[i]);
}
return ReturnVector;
}
And my Drive::GetPhysicalDisks function now takes a vector<DISK_DRIVE_INFORMATION> reference instead of returning one. Seemed to make my program work just fine after that.