MySQL++ - Run-Time Check Failure #2 - Stack around the variable was corrupted - c++

im having issues with MySQL++ and desperately need help.
I'm using Visual Studio 2010, MySQL++ v3.1.0 and MySQL v5.1.59( x86 & x64 );
All Library's have been compiled correctly. This error only occurs in Debug version due to the compiler setting "Both (/RTC1, equiv. to /RTCsu) (/RTC1)" being on.
Edit: I should note that this only happens in Debug version. In Release it works like a charm
I've tracked the problem back to the mysqlpp_d.dll, the MySQL++ object are crashing on there destructors due to reference counting. It complains about not being capable of accessing the memory of the ref counter, and when it tries to decrease it, it crashes. At least thats what I think happens.
I tried this to make sure everything gets derefrenced and removed in the correct order (even tho its irrelevant, but helped me track the true problem down I hope): http://pastebin.com/Ru0uYcy9
It crashes with:
First-chance exception at 0x000007feeef5dd4c (mysqlpp_d.dll) in Launcher.exe: 0xC0000005: Access violation writing location 0x000007feeeff5148.
Unhandled exception at 0x000007feeef5dd4c (mysqlpp_d.dll) in Launcher.exe: 0xC0000005: Access violation writing location 0x000007feeeff5148.
And breakes here:
http://pastebin.com/9Mfr7NwB

This code has a serious bug:
mysqlpp::UseQueryResult res;
{
mysqlpp::Query query = conn.query();
query << "SELECT USER();";
res = query.use();
row = res.fetch_row();
}
You aren't consuming all the result sets. In MySQL, stored procedures that return data return at least two separate result sets: the first is the results you asked for, and the second is status information about the call itself. See examples/multiquery.cpp in the MySQL++ source distribution for the correct way to handle this. Also see section 3.16 in the MySQL++ user manual.
The main consequence of this is that later queries on the same connection will fail.
I think your memory corruption is actually a secondary effect, and that the primary problem stems from ignoring the MySQL C API's attempts to tell you that you're trying to run two overlapping queries on the same connection, because you didn't consume the entire first result set. From what little code you've posted, I can see that you're ignoring returned error codes, so if you've also disabled MySQL++ exceptions, your code will completely ignore this error and blithely go on to stomp all over things it shouldn't.
By the way, please lose the trailing semicolon on the query. It isn't needed with the C API, and can cause confusion, especially in the face of multi-queries. Use semicolons only to separate multiple statements in a single query.

Related

Access Reading Violation when writing a DICOM with vtkDICOMWriter

I'm trying to write vtkImageData as a DICOM. I keep getting an "Access Reading Violation" when I try to write the image.
Unhandled exception at 0x00007FFDA30ECA50 : 0xC0000005: Access violation reading location 0x000001BD38D5C000
Here is my code:
vtkSmartPointer<vtkDICOMWriter> dcmWriter = vtkSmartPointer<vtkDICOMWriter>::New();
dcmWriter->SetInputData(testDat);
dcmWriter->SetFileName(fullPath.toStdString().c_str());
dcmWriter->Update(); // this line breaks
dcmWriter->Write();
testDat is a vtkSmartPointer<vtkImageData> type and has data in it. Any thoughts on whats causing the error? I can't find anything similar online.
I followed this example: https://github.com/dgobbi/vtk-dicom/blob/master/Examples/TestDICOMWriter.cxx
I don't have metadata, but that shouldn't be a problem.
I need to make some guesses here because you didn't post all of your code, but I suspect that the problem happens in the following line:
dcmWriter->SetFileName(fullPath.toStdString().c_str());
toStdString() is most probably returning a temporary std::string (fullPath looks like a Qt QString), on which you call c_str(). After the statement, your temporary is destroyed and whatever you have passed to SetFileName is now a dangling pointer. Hence the segfault.
Try the following instead::
const auto pathString = fullPath.toStdString();
dcmWriter->SetFileName(pathString.c_str());
This should hopefully work fine. Even if not, it definitely is an issue with your code.
These lines are from the example you posted:
writer->SetFilePrefix("/tmp");
writer->SetFilePattern("%s/IM-0001-%04.4d.dcm");
and you use
dcmWriter->SetFileName(fullPath.toStdString().c_str());
It seems that vtkDICOMWriter writes several files so you probably need to provide a file pattern. Anyway, it's hard to guess why it gives a reading error and it's hard to help if you don't post a full working example.
Last, vtkDICOMWriter is not a class from vtk, it was released separetely (it seems) in 2017. This means it's not tested against the rest of VTK at every new release.

Exception handling in Protocol Buffers C++

I don't find anything in Protocol Buffers documentation for exception handling in C++. In Javadoc it has clearly defined ones like InvalidProtocolBufferException, but not in C++.
Sometimes I ran my program and it crashes when it finds missing fields in what it thinks a valid message, then it simply stops and throws errors like this:
[libprotobuf FATAL google/protobuf/message_lite.cc:273] CHECK failed:
IsInitialized(): Can't serialize message of type "XXX" because it is
missing required fields: YY, ZZ
unknown file: Failure
C++ exception with description "CHECK failed: IsInitialized(): Can't
serialize message of type "XXX" because it is missing required fields:
YY, ZZ" thrown in the test body.
The source code of message_lite.cc all wrapped around with "GOOGLE_DCHECK" or "InitializationErrorMessage"...
My application does not allow exceptions like this to halt the program (not sure what the term is in C++ but basically no UncheckedExceptions), so I really need a way to catch these, log errors, and return gracefully, in case some messages got severely corrupted. Is there anyway doing that? Why do I see this post indicating some sort of google::protobuf::FatalException but I couldn't find documentations around it (only FatalException probably not enough also).
Thanks!
The failure you are seeing indicates that there is a bug in your program -- the program has requested to serialize a message without having filled in all the required fields first. Think of this like a segmentation fault. You shouldn't try to catch this exception -- you should instead fix your app so that the exception never happens in the first place.
Note that the check is a DCHECK, meaning it is only checked in debug builds. In your release builds (when NDEBUG is defined), this check will be skipped and the message will be written even though it is not valid. So, you don't have to worry about this crashing your application in production, only while debugging.
(Technically you could catch google::protobuf::FatalException, but the Protobuf code was not originally designed to be exception-safe. Originally, check failures would simply abort the program. It looks like FatalException was added recently, but since the code is not exception-safe, it's likely that you'll have memory leaks any time a FatalException is thrown. So, you probably should treat it like an abort().)
I solved that
my problem was same you.
if another thread change size of proto item while you do serialization then FatalException throw
then at first I copy that in another proto item then I do serialize that.
ProtoInput item; // it is global object
.
.
.
fstream output("myfile",
ios::out | ios::trunc | ios::binary);
ProtoInput in;
in.CopyFrom(item);
size_t size = in.ByteSizeLong();
void *buffer = malloc(size);
if (in.SerializeToArray(buffer, size) == true) {
output.write((char *) buffer, size);
}
output.close();
free(buffer);

CMake Release made my code stop working properly

I have a C++ program which works well when I compile with no additional options. However, whenever I use cmake -DCMAKE_BUILD_TYPE=Release there is a very specific part of the code which stops working.
Concretely, I have an interface for a Boost Fibonacci Heap. I am calling this function:
narrow_band_.push(myObject);
And this function does the following:
inline void myHeap::push (myStruct & c) {
handles_[c.getIndex()] = heap_.push(c);
}
where heap_ is:
boost::heap::fibonacci_heap<myStruct, boost::heap::compare<compare_func>> heap_;
For some reason the heap_size is not being modified, therefore the rest of the code does not work because the next step is to extract the minimum from the heap and it is always empty.
In Debug mode it works ok. Thank you for your help.
EDIT - Additional info
I have also found this problem: I have a set of code which do simple math operations. In Release mode the results are incorrect. If I just do cout of a couple of variables to check their values, the result changes, which is still incorrect but quite strange.
I solved the problem. It was funny but in this case it was not initialization/timing issues common in the Release mode. It was that the return statement was missing in a couple of functions. In debug mode the output was perfect but in the release mode that failed. I had warnings deactivated, that is why I did not see it before.

Interop exception with VC++ and MySQL C++ Connector

I am helping a friend with his bachelor thesis project. It is a program that calculates bending moments for various materials. One of the extra requirements that the client desires is database functionality to store and retrieve various pieces of data being used in the program.
The program is a forms application written in managed C++. I jumped on board to help with writing the database functionality. I am using MySQL Server 5.5 and the MySQL Connector/C++ to bridge the program and the database. Everything has been going pretty well and all the functionality we need works just fine, but only in debug. As soon as we put the program into release mode there is undefined behavior occurring at runtime. Below is the function that is used to open a connection to the database:
try
{
m_driver = get_driver_instance();
m_conn = m_driver->connect(m_dbHost, m_dbUser, m_dbPwd);
m_conn->setSchema(m_dbSchema);
}
catch(sql::SQLException &e)
{
int a = e.getErrorCode();
MessageBoxA(NULL, e.what(), "DB Error", MB_OK);
}
The values passed into the connect function are all std::string. In debug mode the connection is made with no issues. In release mode an exception is caught after the connect function is called, and displays the message "Unknown MySQL Server Host '####' (0)" where the #### is always some garbage text. I also notice that in the output window another exception is being thrown, this one is the type System.Runtime.InteropServices.SEHException.
I have been doing some research and have seen numerous cases of this exception on many forums (and here on stack exchange) but no one seems to be having this issue with the MySQL connector. My assumption is that the memory is being corrupted because the program is mixed mode, with the main program code being written in Managed C++ and my database helper code being in native C++ (as required by the connector).
Is there something I can change in my code to try and fix this issue to that the strings aren't being corrupted at run time. I have tried many different hacks to try and solve the problem but nothing has worked.
Thanks,
Tom
Update: I am now seeing this error in debug mode. I added code to retrieve values from the database and populate some text boxes on the form. The code is as follows:
// Populate the form with material details
String^ selectedMaterial = (String^)(comboBox1->SelectedItem);
string selectedMaterial_ = "";
MarshalString(selectedMaterial, selectedMaterial_);
sql::ResultSet* results = dbHelper.GetData("matname", selectedMaterial_);
if (results->rowsCount() == 1)
{
// Outdim
string outdim_ = "";
outdim_ = results->getString("outdim");
String^ outdim = gcnew String(outdim_.c_str());
textBox1->Text = outdim;
}
else
{
// !!!! Duplicate materials in list
}
When it tries to read outdim from the result set the SEHException is thrown, and the only other piece of information given is that it was thrown in an external component.
Update 2: I ran Application Verifier against the debug executable and then launched the program from VS2010. However the form window never loads so somewhere along the line the program must be getting halted. Strangely there is absolutely no information in the log files in Application Verifier. I also tried with the release version and I didnt get any useful information from that either.

Program crashes with 0xC000000D and no exceptions - how do I debug it?

I have a Visual C++ 9 Win32 application that uses a third-party library. When a function from that library is called with a certain set of parameters the program crashes with "exception code 0xC000000D".
I tried to attach Visual Studio debugger - no exceptions are thrown (neither C++ nor structured like access violations) and terminate() is not called either. Still the program just ends silently.
How does it happen that the program just ends abnormally but without stopping in the debugger? How can I localize the problem?
That's STATUS_INVALID_PARAMETER, use WinDbg to track down who threw it (i.e. attach WinDbg, sxe eh then g.
Other answers and comments to the question helped a lot. Here's what I did.
I notices that if I run the program under Visual Studio debugger it just ends silently, but if I run it without debugger it crashes with a message box (usual Windows message box saying that I lost my unsaved data and everyone is sooo sorry).
So I started the program wihtout debugger, let it crash and then - while the message box was still there - attached the debugger and hit "Break". Here's the call stack:
ntdll.dll!_KiFastSystemCallRet#0()
ntdll.dll!_ZwWaitForMultipleObjects#20() + 0xc bytes
kernel32.dll!_WaitForMultipleObjectsEx#20() - 0x48 bytes
kernel32.dll!_WaitForMultipleObjects#16() + 0x18 bytes
faultrep.dll!StartDWException() + 0x5df bytes
faultrep.dll!ReportFault() + 0x533 bytes
kernel32.dll!_UnhandledExceptionFilter#4() + 0x55c bytes
//SomeThirdPartyLibraryFunctionAddress
//SomeThirdPartyLibraryFunctionAddress
//SomeThirdPartyLibraryFunctionAddress
//SomeThirdPartyLibraryFunctionAddress
//OurCodeInvokingThirdPartyLibraryCode
so obviously that's some problem inside the trird-party library. According to MSDN, UnhandledExceptionFilter() is called in fatal situations and clearly the call is done because of some problem in the library code. So we'll try to work the problem out with the library vendor first.
If you don't have source and debugging information for your 3rd party library, you will not be able to step into it with the debugger. As I see it, your choices are;
Put together a simple test case illustrating the crash and send it onto the library developer
Wrap that library function in your own code that checks for illegal parameters and throw an exception / return an error code when they are passed by your own application
Rewrite the parts of the library that do not work or use an alternative
Very difficult to fix code that is provided as object only
Edit You might also be able to exit more gracefully using __try __finally around your main message loop, something like
int CMyApp::Run()
{
__try
{
int i = CWinApp::Run();
m_Exitok = MAGIC_EXIT_NO;
return i;
}
__finally
{
if (m_Exitok != MAGIC_EXIT_NO)
FaultHandler();
}
}