Using A C++ Class In Windows Form Leads to System.AccessViolationException - c++

I have written a few C++ classes which employ a variety C++ libraries. I made a Windows Form project, and set it up to use my classes successfully. However, I recently made another C++ class and now I consistently get:
A first chance exception of type 'System.AccessViolationException' occurred in TEST_OCU.exe
which leads to:
An unhandled exception of type 'System.TypeInitializationException' occurred in Unknown Module.
Additional information: The type initializer for '<Module>' threw an exception.
The program hasn't even started running yet, and the new, problem-causing C++ class hasn't even been constructed yet. If I comment out the new call, and only have a pointer to this new C++ class, everything compiles just fine. BUT, if somewhere I do something like:
if(new_class_ptr != NULL)
new_class_ptr->SomeFunction() //It doesn't matter what function this is
This will throw those violations again
Some facts:
Compiling and linking is fine, this seems to be a run-time problem.
My solution employs unmanaged C++ libraries and classes (that I have written), and one managed C++ Form.
So far I haven't had any problems, I've used a few C++ libraries successfully for a while. This is caused by a new C++ class I recently wrote.
The C++ class which causes these violations uses std::ifstream to read in a file. If I comment out the std::ifstream input_file(filename); my Forms project runs successfully.
If I use the C++ class in a simple Win32 project, it compiles and runs just fine with the std::ifstream.
I have a strong feeling it is related to this question
Could anyone offer any advice? Thank you
EDIT: I'm providing some parts of my form code I have. RTSPConnection works just fine, the offending class is RTPStream
public ref class Form1 : public System::Windows::Forms::Form
{
public:
// ... Lots of generated code here ...
//Calls I've written
private: static RTSPConnection * rtsp_connection_ = NULL; //This class works
private: static RTPStream * rtp_connection_ = NULL; //This class does not
bool streaming_;
System::Threading::Thread^ streaming_thread_;
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
if(rtsp_connection_ == NULL)
{
rtsp_connection_ = new RTSPConnection("rtsp://192.168.40.131:8554/smpte");
streaming_ = false;
}
//if(rtp_connection_ == NULL)
// rtp_connection_ = new RTPStream("test");
}
private: System::Void Form1_FormClosing(System::Object^ sender, System::Windows::Forms::FormClosingEventArgs^ e) {
if(rtsp_connection_ != NULL)
rtsp_connection_->StopStreaming();
}
private: System::Void button1_MouseClick(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
if(!streaming_)
{
//Start Streaming
streaming_thread_ = gcnew Thread(gcnew ThreadStart(&Form1::WorkerThreadFunc));
streaming_thread_->Start();
this->button1->Text = L"Stop Streaming";
streaming_ = true;
}
else
{
//Stop Streaming
if(rtsp_connection_ != NULL)
rtsp_connection_->StopStreaming();
//THIS CALL RIGHT HERE WILL THROW AN ACCESS VIOLATION
if(rtp_connection_ != NULL)
rtp_connection_->StopStreaming();
this->button1->Text = L"Start Streaming";
streaming_ = false;
}
}
};

These two statements appear to contradict each other:
The program hasn't even started running yet, and the new,
problem-causing C++ class hasn't even been constructed yet.
If I comment out the new call, and only have a pointer to this new C++
class, everything compiles just fine.
Q: Could you please post the code where you're calling "new"? Or are you calling "new" - perhaps you just meant "if I comment out my new class"?
Q: Could you please set a breakpoint in your constructor, look at the stack trace, and see who's invoking it? And when?
========== ADDENDUM ==========
I strongly disagree with this statement:
It all hinges on this line: std::ifstream input_file(filename);
where filename is a std::string.
I strong AGREE with this statement:
You get almost the same error in C# if you have static class members
that depend on each other and they aren't initialised in the order you
expect. In C++, if you had a static singleton and another static
member that referred to it
Calling "ifstream" isn't the problem per se. Rather, somehow invoking the class that invokes ifstream before the program has initialized is the problem.
Q: Are you calling "new" on this class? If so, where. Please cut/paste that code.
Per MSDN, you should be able to set "mixed mode debugging". I have lots of different copies of MSVS :) ... but MSVS 2010/C++ doesn't happen to be one of them. Please look at this documentation:
http://msdn.microsoft.com/en-us/library/fz5w87ad.aspx
http://msdn.microsoft.com/en-us/library/cktt23yw

Related

C++ code throwing Seg. Fault

I have a C++ code as follow:
tryIt.h file
class tryIt : public someOtherClass
{
public:
bool insertI ();
private:
CommandI* m_pInsertI;
bool createInsertI();
}
tryIt.cpp file
tryIt ::tryIt () : m_pInsertI(NULL)
{
createInsertI();
}
tryIt ::~tryIt ()
{
if(m_pInsertI!=NULL)
{
delete m_pInsertI;
m_pInsertI=NULL
}
}
bool createInsertI()
{
m_pInsertI = returnFromSomeOtherFunction();
return true;
}
bool insertI()
{
// Over here if I use m_pInsertI anyhow my code fails with seg fault
// even checking if(m_pInsertI==NULL) make the code throw seg fault
}
So the issue is touching m_pInsertI anywhere make my code throw Seg. fault (Signal 11). Even debugged the code with GDB but didn't got any useful info.
Compiler is GCC
Please help.
Sounds like the instance of this class does not exist or damaged.
That is why you can't access any of its members and even if(m_pInsertI==NULL) check raises the exception.
in tryIt.cpp shouldn't
bool createInsertI()
be
bool tryIt::createInsertI()
same with insertI()
I see the following two possibilities:
returnFromSomeOtherFunction() already returns a corrupted pointer
You are copying your instance using the compiler generated methods (see example below)
Example (Rule of three violation)
tryIt instance1; // allocates instance2.m_pInsertI
{
tryIt instance2;
instance1 = instance 2; // performs a shallow copy
} // here, instance2.m_pInsertI is deleted
instance1.insertI(); // access violation
Recommendation:
Whether or not this is cause your problem: Do not implement manual memory management. Simply use a std::unique_ptr<CommandI> for m_pInsertI instead, so you do not need to implement the destructor or copy constructors/operators.

error codes for C functions under C++11? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm currently using a C library under C++11, the problem that I'm facing now and I never faced before, it's to handle errors and failures in a way that will be meaningful for the end user of my program.
At the moment in my C++ code there is something as assert(foo()), where foo is a function from this C library and it returns a bool which reflects the state of the operations, true everything is ok, false otherwise.
I'm wondering if there is a better way to handle this, I would like to substitute the default message with some custom error code or a different string/message. Also note that I can't modify this library, so any possible solution needs to take this into account.
The are 2 main points that concern me:
assert is for when I compile my code in debug, I will basically never use assert in production or release mode, nor assert is intended to be used like I'm using it for the moment
a good portion of this functions is highly influenced by user input, so something that works at runtime is highly needed .
What should I do ? I basically have a C function that returns a bool, it doesn't uses any C or C++ specific error handling function or macro, I should wrap it inside a try catch ?
I'm also taking into account the fact that I would like to avoid calling std::abort and I would prefer to clean up everything in case of failure.
I would use C++ exceptions.
You can use some of the already defined standard C++ exception classes, like std::runtime_error, or you can define some custom exception class (derived from e.g. std::runtime_error).
e.g.
// FooWrapper.h -- C++ wrapper around your "foo" library
#pragma once
#include <stdexcept> // For std::runtime_error
#include "foo.h" // The C library header
...
namespace Foo { // Can wrap the raw C library nicely in a namespace
// Custom exception class for your "foo" errors.
class FooError : public std::runtime_error {
public:
explicit FooError(const std::string& errorMessage)
: std::runtime_error(errorMessage) {
// Can do additional initialization stuff, and pass
// additional information regarding the particular "Foo" error,
// e.g. as another constructor parameter.
// ...
}
};
... other stuff in the wrapping header ...
} // namespace Foo
Then, in your C++ code, you can throw the aforementioned exception when foo() function call fails:
if (! foo()) {
throw Foo::FooError("Some information", ...some other error params... );
}
And you can catch that and try to recover or print a nice error message in the GUI part of your code, e.g.:
try {
// ... do something ...
} catch( const Foo::FooError& fooError ) {
// ... try to recover, or display the error message
// returned by fooError.what()
}
Note also that, since the FooError exception class is inserted into the standard C++ exception hierarchy (since it's derived from std::runtime_error), this custom exception can also be caught by C++ code already present in your code base, that tries to catch the more generic std::runtime_error or std::exception classes.
Put all entry points to the library in your code within try/catch blocks as you suggested. Then the quickest and simplest solution is
if (!foo())
throw std::runtime_error("foo(): returned false");
as needed. You can create your own exception class (possibly but not necessarily derived from std::exception when you decide you need more structured behavior, e.g. behavior which depends on exactly which function fails. In the simple case you would just have
try
{
... //The if/throw test will typically not occur here, but deeper within the call stack.
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
//do cleanup
}
or something like that. Edit: As #TNA emphasizes, you put the try/catch block at the point in the code where you are able to handle the error. The if/throw tests can occur anywhere.
If macro and go to statement can be considered, I think this can be an alternative:
#define CHECK (fn) if (!fn) \
{ \
// Set the valid error msg somewhere that can be retrieved later on..
goto QUIT; \
} \
// Usage
AnyObject Afnc()
{
AnyObject anyObj;
CHECK(foo())
QUIT:
return anyObj;
}

About _variant_t type in a MFC Library

inside my MFC (VC2010 SP1) project, I'm widely using a third party library to write some data in a database. This library is quite old (I've found it compiled for VS2005) and uses _variant_t to handle data.
In a particular case anyway I get a strange behaviour, I'll try to explain it:
// .h
struct myData
{
blastuff
CString strMyCode;
};
class MyClass
{
protected:
myData m_Foo;
};
// .cpp
// In OnInitDialog:
//...
TrdPartRecordset *pRS;
//...
pRS->GetFieldValue( _T("MyDBColumn"), m_Foo.strMyCode );
Now, I do my job and when user press OK, it's time to save to database and here start the problems:
// In OnOK
TrdPartRecordset *pRS;
//...
pRS->SetFieldValue( _T("MyDBColumn"), m_Foo.strMyCode );
Problem: if I do not modify m_Foo.strMyCode, I don't have any problem. What if I modify it? Well, if m_Foo.strMyCode does NOT contain ANY number, still have no problem.
Instead, when I have a number, I get a nasty error:
Unhandled exception at 0x77772d37 in Mosaico.exe: 0xC0000005: Access violation reading location 0x9d7077b7.
which is an attempt to read a deleted location. I've checked m_Foo in the watch and it's correct and valid, so I've digged into library source code:
BOOL TrdPartyRecordset::SetFieldValue(LPCTSTR lpFieldName, CString strValue)
{
_variant_t vtFld;
if(!strValue.IsEmpty())
vtFld.vt = VT_BSTR;
else
vtFld.vt = VT_NULL;
vtFld.bstrVal = strValue.AllocSysString();
BOOL bret = PutFieldValue(lpFieldName, vtFld);
SysFreeString(vtFld.bstrVal);
return bret;
}
What it happens is that vtFld is valid until SysFreeString and it get destroyed after it (I can see it proceding step-by-step with debugger), but ONLY WHEN I HAVE NUMBERS INTO strValue. This doesn't happen when strValue is pure alphabetical.
I've searched around the Internet and found that this kind of error happens when you double release a resource and so I've commented out SysFreeString and boom goes the dynamite: no more crashes.
Anyway is a better programmer than me so I guess that if he put that SysFreeString he had his reasons, moreover, this is the only part of my program where this mechanism crashes.
My question is: do I lose memory commenting out that SysFreeString?
Another one: do you have better solutions?
The reason is simple:
The memory is freed twice!
_variant_t has a destructor. Set the type to VT_BSTR. You also see the pojnter and type to VT_BSTR
After the function you call, you free the memory again and the destructor does the same.
The code should look like this:
_variant_t vtFld;
if(!strValue.IsEmpty())
vtFld = strValue;
else
vtFld.vt = VT_NULL;
return PutFieldValue(lpFieldName, vtFld);

Debug version only crash

I'm having a debug only crash. I'm using Eclipse's gdb.
If I'm not failing reading it, the crash seems to occur when passing an object (not by reference nor pointer) to an interface method, precisely when copying a "many" (typedef std::list<boost::any> many;) member during it's copy constructor called to send a copy to the method.
I'm not using debug builds for boost, nor other external builds, just for the code I'm compiling, so, could this be the cause?
Any other ideas at what may be the cause?
class Message {
public:
static const int MAX_LEVEL=5;
Message(int type=0, int destination=0);
virtual ~Message();
int type;
int destination[MAX_LEVEL];
int level;
many message;
};
And the crashing sector, inside init() on Game3DWin: (Even though I'm building in Debug mode, there's no _DEBUG define since I didn't build the Debug binaries for the libs)
bool Game3DWin::init(){
#ifdef _DEBUG
pluginsCfg = "lib/plugins_d.cfg";
resourcesCfg = "res/resources_d.cfg";
#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32
pluginsCfg = "lib/pluginsWin.cfg";
resourcesCfg = "res/resources.cfg";
#else
pluginsCfg = "lib/plugins.cfg";
resourcesCfg = "res/resources.cfg";
#endif
ogreRoot=boost::make_shared<Ogre::Root>(pluginsCfg, "config.cfg");
if(!(ogreRoot->restoreConfig() || ogreRoot->showConfigDialog())){
return false;
}
window = ogreRoot->initialise(true, "Crewon CLASH!");
loadResourceCfgFile();
guiRenderer = &CEGUI::OgreRenderer::bootstrapSystem();
CEGUI::SchemeManager::getSingleton().create( "TaharezLook.scheme" );
CEGUI::System::getSingleton().setDefaultFont( "DejaVuSans-10" );
CEGUI::System::getSingleton().setDefaultMouseCursor( "TaharezLook", "MouseArrow" );
CEGUI::Window* myRoot = CEGUI::WindowManager::getSingleton().createWindow( "DefaultWindow", "_MasterRoot" );
CEGUI::System::getSingleton().setGUISheet( myRoot );
CRengine::Message msg=CRengine::Message( (int)CRengine::MESSAGE_TYPE::INPUT_INIT );
msg.message.push_front(window);
this->broadcaster.lock()->receiveMessage( msg ); //Crash here
//Unreached code due to crash
}
broadcaster is a pointer to Messageable, an interface.
class Messageable {
public:
virtual ~Messageable() {};
virtual bool receiveMessage(CRengine::Message) = 0;
};
broadcaster initialization (factory method to be able to store a "this" smart pointer):
Game3DWin* Game3DWin::create(boost::shared_ptr<CRengine::Messageable> caster, int processType, int order){
Game3DWin* temp= new Game3DWin(processType, order);
temp->broadcaster=caster;
bool success=temp->init();
if(!success){
delete temp;
temp=NULL;
}else{
temp->checkRoom(); }
return temp;
}
The above is called here:
bool MainManager::start( boost::shared_ptr<MainManager> thisMM ){
//Some code
boost::shared_ptr<Game3DWin> win;
win.reset( Game3DWin::create(thisMM, CRengine::MAIN_PROCESS_TYPES::PROCESS_GUI) );
//Some code
}
start() called from the main, which passes the pointer to MainManager
boost::shared_ptr<CRengine::MainManager> app =boost::make_shared<CRengine::MainManager>();
app->start(app);
Message implementation:
Message::Message(int type, int destination): type(type), level(0){
for(int ii=0;ii<MAX_LEVEL;ii++){
this->destination[ii]=-1;
}
this->destination[0]=destination;
}
Message::~Message() { }
window is Ogre::RenderWindow* from OGRE 3D open source rendering engine. I tried to cast it to (int) before pushing it into many in case it tried to call a destructor or something, but, still, same crash.
This is an extended comment, too long to fit in a comment.
Message lacks an implemented constructor and destructor. Either simplfy the class while confirming the problem still occurs, or expose that implementation to us.
window is a variable of unknown type. As the list of boost::any that you are reporting as crashing contains the window type, knowing what it is may just be somewhat useful.
this->broadcaster.lock() will be a null shared_ptr if the weak_ptr has gone away. Always, always, always do shared_ptr<foo> pFoo = this->broadcaster.lock(); then use pFoo (or whatever name) after checking that it is valid (evaluating it in a boolean context).
boost::weak_ptr<CRengine::Messageable> caster -- do you not know if this exists? You probably want a boost::shared_ptr here, so that the caster is at least known to exist during creation of the Game3DWin.
Same here: boost::weak_ptr<MainManager> thisMM -- probably should be a shared_ptr.
The issue was none of the aforementioned. It was caused by Eclipse being unable to clean. This was caused due to using "External Builder", mingw32-make.exe, which in the makefile ran a del <Filelist> and Windows7 seems to have some issue with this and it's parameters, so the clean did nothing.
Since I was working with Debug as active build, I got the crash due to lack of clean, but when I switched to Release it was unaffected since it had to mostly rebuild everything.
Manual delete of the contents of <project>/Debug and <project>/Release fixed the problem.

Angelscript class method registration

I am writing some basic code to experiment with Angelscript, however I cannot get even the simplest functions to work correctly. Here is the basic code block:
class Engine {
public:
void print(std::string&);
};
Engine::print(std::string &msg)
{
cout<<msg.c_str()<<endl;
}
Here is the actual code that initializes and registers C functions for Angelscript:
int r;
asIScriptEngine *engine = asCreateScriptEngine(ANGELSCRIPT_VERSION);
r = engine->SetMessageCallback(asMETHOD(Engine,MessageCallback), this,asCALL_THISCALL);
assert( r >= 0 );
RegisterStdString(engine);
r = engine->RegisterObjectType("Engine", 0, asOBJ_APP_CLASS_CONSTRUCTOR);
cout<<"r was: "<<r<<endl;
assert( r >= 0 );
r = engine->RegisterObjectMethod("Engine","void print(const string &in)", asMETHOD(Engine,print), asCALL_THISCALL);
assert( r >= 0 );
At first I did not have the function "RegisterObjectType()" present, so running the program would throw a "'Engine' is not a valid type" error even though it was a valid class. So I found a function called "RegisterObjectType()" and implemented it as above and now it's throwing a "Invalid Flag" error on the 'RegisterObjectType()' function in the last field. I've tried all the class flags and it still throws this error.
What is the proper method for registering a class method into Angelscript? The documentation example didn't seem to work. It seems to snip out everything except the actual function it is explaining, for example, it did not hint about registering object types with the class method registration code. Or it was not very clear about it.
I should mention that all the errors encountered are runtime errors thrown by the angelscript libraries and not compiler errors.
Thanks!
The as_OBJ_APP_CLASS_CONSTRUCTOR is not proper flag, it should be used combined with other as_OBJ_APP... flags. Check this for example (bit outdated), and clarifications of ways to register object type: http://www.darawk.com/code/CoHClient/Angelscript/sdk/docs/articles/register_object.html.
Of course manual is your best friend:
http://www.angelcode.com/angelscript/sdk/docs/manual/index.html
(Using Angelscript->Registering the application interface->Registering an object type)