I'm learning exceptions in C++ and I was trying this:
int main(int argc, char* argv[]) {
double *p_x;
try {
p_x = new double[100000000000000];
delete p_x;
} catch (bad_alloc& ex) {
cout << "Memory not allocated !!\n";
}
return 0;
}
The exception gets caught but there's other stuff printed when executing this code. The output looks like:
Memory not allocated !!
Test9(13814) malloc: *** mmap(size=800000000000000) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
I don't know if it's somehow related to the version of g++ or maybe related to the OS X.
I mean, the program is catching the exception but what is the other stuff about?
It's glibc related. You can disable these messages with the mallopt(3) command:
mallopt(M_CHECK_ACTION, 0);
Related
what I'm trying to do is integrate a MATLAB-Compiler dll/lib to an new c++ project.
I followed this instruction: How do I integrate my C++ shared Library generated from MATLAB which seams working good (no build errors and intelisense is working good, so it seams all required information are there).
I'm using a very simple mathlab code / function for testing:
function output = extest( arg1,arg2 )
output = arg1+arg2;
end
And the "default" c++ code for matlab functions:
#include "extest.h"
#include <cstdlib>
#include <stdio.h>
int main(int argc, char** argv){
mclmcrInitialize();
if (!mclInitializeApplication(NULL,0)){
std::cerr << "could not initialize the application properly" << std::endl;
return -1;
}
if(!extestInitialize()){
std::cerr << "could not initialize the library properly" << std::endl;
return -1;
}
else{
try{
//code itself (not jet reached therefore removed)
}catch(const mwException& e){
std::cerr << e.what() << std::endl;
return -2;
}
catch(...){
std::cerr << "Unexpected error thrown" << std::endl;
return -3;
}
extestTerminate();
}
mclTerminateApplication();
return 0;
}
After e few moments after the debugger tries to run the line if(!extestInitialize()) the following error gets thrown.
Exception thrown at 0x000002BF72E0EE55 in DllTestingCpp.exe: 0xC0000005: Access violation reading location 0x0000000000000008.
I can hit visual studios continue > button and it is continued after lets say 20x click on it. Starting the code by ctrl + F5 (without debugging) everything is working good.
Any ideas why this happens in debug mode? Or better how I can get rid of this error?
PS: extest is my lib name and using Matlab R2017a 64bit and Visual Studio 2017 (debugging with x64),
The same problem (Matlab2017 + VS 2015) for me.
Probably there is some conflict with java used by MATLAB.
I've fixed it by
const char *args[] = {"-nojvm"};
const int count = sizeof(args) / sizeof(args[0]);
mclInitializeApplication(args, count))
instead of
mclInitializeApplication(NULL,0)
I had the same issue(using VS2019) and I found the following answer here:
https://uk.mathworks.com/matlabcentral/answers/182851-how-do-i-integrate-my-c-shared-library-generated-from-matlab-r2013b-in-visual-studio-2013
I encountered this same issue and reported it to Mathworks. They responded that for VS2013 and later, the debugger is set to break when 0xc0000005 occurs, even though in this case it is handled by the JVM.
The fix is to go to Debug>Windows>Exception Settings>Win32 and uncheck '0xc0000005 Access Violation'. In VS2012, this setting is unchecked by default.
This seems to work o.k.
I'm trying to write some C code that calls some python code to do some data analysis, and I came upon a weird issue. If I call initialize python, call a function, finalize python, and then repeat the same 1 time, I get an access violation writing location error the second time I try to call the function. The following simple code:
#include "stdafx.h"
#include <iostream>
#include "Python.h"
int main()
{
for (int testInc = 0; testInc < 2; testInc++)
{
std::cout << testInc + 1 << std::endl;
PyObject *pName, *pModule, *pFunc, *pValue;
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\"PathToCode\")");
pName = PyUnicode_DecodeFSDefault("MyModuleName");
pModule = PyImport_Import(pName);
pFunc = PyObject_GetAttrString(pModule, "MyFunctionName");
pValue = PyObject_CallObject(pFunc, NULL);
printf("Result: %s\n", PyBytes_AS_STRING(PyUnicode_AsEncodedString(pValue, "ASCII", "strict")));
Py_DECREF(pName);
Py_DECREF(pModule);
Py_DECREF(pFunc);
Py_DECREF(pValue);
Py_Finalize();
}
return 0;
}
(checks on Py_Object*'s being == NULL omitted for brevity, but they all pass). With the python code being:
def myFunctionName():
import numpy
return "Hi!"
consistently throws the error "Unhandled exception at 0x00007FFE1EBC199C (multiarray.cp35-win_amd64.pyd) in TestApplication.exe: 0xC0000005: Access violation writing location 0x000000000000000A." on the second pass through the for loop, and I'm struggling to figure out why. If I place the initialize and finalize commands outside of the for loop, then this works fine, but my understanding of these commands leads me to believe that this code should be functional. Also, if I omit the "import" command in the python script, my C code also runs fine then, leading me to believe that something weird is happening with the import. Am I misunderstanding something?
I have a C++ application which terminates with a "bad allocation" error message for certain input data on an AIX machine.
Is there a way to run the program in dbx and catch the exception when it's being thrown? I don't see anything about it in IBM's documentation.
If your C++ application is compiled with XL C/C++, set a breakpoint on __DoThrowV6.
$ cat throw.C
int foo(int x)
{
if (x < 0)
throw 99;
return x+1;
}
int main()
{
int y;
y = -5;
try
{
foo(y);
}
catch(...)
{
}
return 0;
}
$ xlC -g -o throw throw.C
$ dbx ./throw
Type 'help' for help.
reading symbolic information ...
(dbx) stop in __DoThrowV6
[1] stop in __DoThrowV6
(dbx) run
[1] stopped in __DoThrowV6 at 0xd1be7e00
0xd1be7e00 (__DoThrowV6) 7c0802a6 mflr r0
(dbx) where
__DoThrowV6() at 0xd1be7e00
foo(int)(x = -5), line 4 in "throw.C"
main(), line 14 in "throw.C"
(dbx)
__DoThrowV6 is called when an exception is thrown, so from the call stack one can see that the exception was thrown from line 4 of the source file throw.C
This is my first attempt to write a custom exception class implementing a simple form of stack-trace.
This is the .h:
class error {
public:
error ();
error (const error & err);
~error ();
int level ();
private:
int _level;
};
And this is the .cpp:
error::error ()
: _level (0) {}
error::error (const error & err)
: _level (err._level) {}
error::~error () {}
int error::level () {
return ++_level;
}
Then I define two macros, one to create an error and throw it the first time (INIT_ERROR), and the other to kick the catched errors (KICK_ERROR):
#define WHERE(stream) {fprintf (stream, " %-30s [%s: %3d]\n", __FUNCTION__, __FILE__, __LINE__);}
#define INIT_ERROR {fprintf (stderr, "# 0"); WHERE (stderr); throw error ();}
#define KICK_ERROR {fprintf (stderr, "# %2d", err.level ()); WHERE (stderr); throw;}
As you expect, the use is as follow:
if (something wrong)
INIT_ERROR;
for the first time, and:
try {
// some code
}
catch (error & err) {
KICK_ERROR;
}
for all the other times.
However, DrMemory (I'm working on Windows Xp), alert me about still reachable blocks:
ERRORS FOUND:
0 unique, 0 total unaddressable access(es)
0 unique, 0 total uninitialized access(es)
0 unique, 0 total invalid heap argument(s)
0 unique, 0 total GDI usage error(s)
0 unique, 0 total warning(s)
0 unique, 0 total, 0 byte(s) of leak(s)
0 unique, 0 total, 0 byte(s) of possible leak(s)
3 unique, 3 total, 16 byte(s) of still-reachable allocation(s)
ERRORS IGNORED:
3 potential leak(s) (suspected false positives)
For completeness, this is the main:
void fun3 () {
fprintf (stderr, "nothing special");
INIT_ERROR;
}
void fun2 () {
try {
fun3 ();
}
catch (error & err) {
KICK_ERROR;
}
}
void fun1 () {
try {
fun2 ();
}
catch (error & err) {
KICK_ERROR;
}
}
int main () {
try {
fun1 ();
}
catch (error & err) {
cerr << "error catched in main" << endl;
}
}
Is this something wrong in my code?
Suggestions?
Still reachable allocations are not leaks, this is memory that is still available to the program at exit. It might be allocated from the libraries you use. I would not worry about them.
I don't think that there are any leaks. Your code seems valid. I think that the three blocks are just the allocated objects that were still alive at the precise point of time when program was starting its cleanup-on-death, if you might call that so.
I mean, something trivial like, std::cout, your exception and some lingering temporary string ;)
If you'd like to verify that, add a top-level TRY/CATCH at the most outer scope od MAIN that calls your exception test, so that the exception will be actually caught, stack unwound and so that the program will exit normally. That way, after catch/unwind, the lingering exception object and other should be cleaned up and probalby you will see LESS still-reachables.
Not necessarily zero, that depends on libraries used and the way that "DrMemory" of yours account for CRT "baseline memory footprint", sorry I don't know how to call that better..
I've been "playing around with" boost threads today as a learning exercise, and I've got a working example I built quite a few months ago (before I was interrupted and had to drop multi-threading for a while) that's showing unusual behaviour.
When I initially wrote it I was using MingW gcc 3.4.5, and it worked. Now I'm using 4.4.0 and it doesn't - incidentally, I've tried again using 3.4.5 (I kept that version it a separate folder when I installed 4.4.0) and it's still working.
The code is at the end of the question; in summary what it does is start two Counter objects off in two child threads (these objects simply increment a variable then sleep for a bit and repeat ad infinitum - they count), the main thread waits for the user via a cin.get() and then interrupts both threads, waits for them to join, then outputs the result of both counters.
Complied with 3.4.5 it runs as expected.
Complied with 4.4.0 it runs until the user input, then dies with a message like the below - it seems the the interrupt exceptions are killing the entire process?
terminate called after throwing an instance of '
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
boost::thread_interrupted'
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
From what I read, I think that any (?) uncaught exception that is allowed to propagate out of a child thread will kill the process? But, I'm catching the interrupts here, aren't I? At least I seem to be when using 3.4.5.
So, firstly, have I understood how interrupting works?
And, any suggestions as to what is happening and how to fix?
Code:
#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/date_time.hpp>
//fixes a linker error for boost threads in 4.4.0 (not needed for 3.4.5)
//found via Google, so not sure on validity - but does fix the link error.
extern "C" void tss_cleanup_implemented() { }
class CCounter
{
private:
int& numberRef;
int step;
public:
CCounter(int& number,int setStep) : numberRef(number) ,step(setStep) { }
void operator()()
{
try
{
while( true )
{
boost::posix_time::milliseconds pauseTime(50);
numberRef += step;
boost::this_thread::sleep(pauseTime);
}
}
catch( boost::thread_interrupted const& e )
{
return;
}
}
};
int main( int argc , char *argv[] )
{
try
{
std::cout << "Starting counters in secondary threads.\n";
int number0 = 0,
number1 = 0;
CCounter counter0(number0,1);
CCounter counter1(number1,-1);
boost::thread threadObj0(counter0);
boost::thread threadObj1(counter1);
std::cout << "Press enter to stop the counters:\n";
std::cin.get();
threadObj0.interrupt();
threadObj1.interrupt();
threadObj0.join();
threadObj1.join();
std::cout << "Counter stopped. Values:\n"
<< number0 << '\n'
<< number1 << '\n';
}
catch( boost::thread_interrupted& e )
{
std::cout << "\nThread Interrupted Exception caught.\n";
}
catch( std::exception& e )
{
std::cout << "\nstd::exception thrown.\n";
}
catch(...)
{
std::cout << "\nUnexpected exception thrown.\n"
}
return EXIT_SUCCESS;
}
Solved.
It turns out adding the complier flag -static-libgcc removes the problem with 4.4.0 (and has no apparent affect with 3.4.5) - or at least in this case the program returns the expected results.