C++ Delete Error -- _unlock_fhandle throwing exception? - visual-c++

I have a straightforward problem but I don't understand why I have it.
I would greatly appreciate any insight.
I wrote this code to test that I was correctly creating and using DLLs in Visual Studio 2010 under Win 7 64bit that could execute on Windows XP. The code executes correctly, and because it is a small test program freeing the allocated memory is not critical, but certainly will be in the future.
I am implicitly calling the DLL, as I say, it appears to work just fine. When I add the line "delete dllMsg;" to toyUseDLL.cpp it crashes, and the debugger shows _unlock_fhandle in osfinfo.c.
If it's relevant I am compiling the program with /MT to embed the runtime library (for a small handful of not important reasons).
It seems pretty obvious that I'm deallocating something not allocated, but the program output is correct since the pointers are passing the referenced memory locations. The only thing I can think of is that my pointer isn't valid, and it's only working by pure chance that the memory wasn't overwritten.
Thanks for any help, I'm pretty new to C++ and have already found a lot of great help on this site, so thanks for everyone who has posted in the past!! :-)
msgDLL.h
#include <string>
using namespace std;
namespace toyMsgs {
class myToyMsgs {
public:
static __declspec(dllexport) string* helloMsg(void);
static __declspec(dllexport) string* goodbyeMsg(void);
};
}
msgDLL.cpp
#include <iostream>
#include <string>
#include "msgDLL.h"
using namespace std;
namespace toyMsgs {
string* myToyMsgs::helloMsg(void) {
string *dllMsg = new string;
dllMsg->assign("Hello from the DLL");
cout << "Here in helloMsg, dllMsg is: \"" << *(dllMsg) << "\"" << endl;
return (dllMsg);
}
string* myToyMsgs::goodbyeMsg(void) {
string *dllMsg = new string;
dllMsg->assign("Good bye from the DLL");
cout << "Here in goodbyeMsg, dllMsg is: \"" << *(dllMsg) << "\"" << endl;
return (dllMsg);
}
}
toyUseDLL.cpp
#include <iostream>
#include <string>
#include "stdafx.h"
#include "msgDLL.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[]) {
string myMsg;
string *dllMsg;
myMsg.assign ("This is a hello from the toy program");
cout << myMsg << endl;
dllMsg = toyMsgs::myToyMsgs::helloMsg();
cout << "Saying Hello? " << *(dllMsg) << endl;
delete dllMsg;
myMsg.assign ("This is the middle of the toy program");
cout << myMsg << endl;
dllMsg = toyMsgs::myToyMsgs::goodbyeMsg();
cout << "Saying goodbye? " << *(dllMsg) << endl;
myMsg.assign ("This is a goodbye from the toy program");
cout << myMsg << endl;
return 0;
}
Program Output:
This is a hello from the toy program
Here in helloMsg, dllMsg is: "Hello from the DLL"
Saying Hello? Hello from the DLL
This is the middle of the toy program
Here in goodbyeMsg, dllMsg is: "Good bye from the DLL"
Saying goodbye? Good bye from the DLL
This is a goodbye from the toy program

The problem is that you are using /MT to compile your EXE and DLL. When you use /MT, each executable gets its own copy of the C runtime library, which is a separate and independent context. CRT and Standard C++ Library types can't safely be passed across the DLL boundary when both DLLs are compiled /MT. In your case the string is allocated by one CRT (on its private OS Heap), and freed by the EXE (which has a different heap) causing the crash in question.
To make the program work, simply compile /MD.
General advice: /MT is almost never the right thing to do (for a large handful of relatively important reasons including memory cost, performance, servicing, security and others).
Martyn

There is some good analysis here Why does this program crash: passing of std::string between DLLs

Related

Reading and writing different files in their own threads from my main loop in C++11

I am trying to understand, then, write some code that has to read from, and write to many different files and do so from the main loop of my application. I am hoping to use the C++11 model present in VS 2013.
I don't want to stall the main loop so I am investigating spinning off a thread each time a request to write or read a file is generated.
I've tried many things including using the async keyword which sounds promising. I boiled down some code to a simple example:
#include <future>
#include <iostream>
#include <string>
bool write_file(const std::string filename)
{
std::cout << "write_file: filename is " << filename << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
std::cout << "write_file: written" << std::endl;
return true;
}
int main(int argc, char* argv[])
{
const std::string filename = "foo.txt";
auto write = std::async(std::launch::async, write_file, filename);
while (true)
{
std::cout << "working..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "write result is " << write.get() << std::endl;
}
}
I'm struggling to understand the basics but my expectation would be that this code would constantly print "working..." and interspersed in the output would be the write_file start and end messages. Instead, I see that the write_file thread seems to block the main loop output until the timer expires.
I realize I need to also consider mutex/locking on the code to actually write the file but I would like to understand this bit first.
Thank you if you can point me in the right direction.
Molly.
write.get() will wait for the async task to finish. You want to use wait_for() instead:
do {
std::cout << "working...\n";
} while(write.wait_for(std::chrono::milliseconds(100)) != std::future_status::ready);
std::cout << "write result is " << write.get() << "\n";

Uninitialized local variable 'state' used

So I want to create a program which allows users to map buttons to keyboard presses using c++ with Visual Studio 2015. I have been having a ton of trouble with Xinput and I was hoping someone could help me with one simple problem which makes no sense seeing as I have defined it.
So my problem is I get one error which says unresolved external symbol _XinputGetState#8 referenced in function _main.
Here is my code:
#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <Xinput.h>
using namespace std;
int main() {
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
if (XInputGetState(0, &state) == ERROR_SUCCESS)
{
cout << "It worked!" << endl;
}
bool A_button_pressed = ((state.Gamepad.wButtons & XINPUT_GAMEPAD_A) != 0);
cout << A_button_pressed << endl;
}
In general unresolved external symbols means that a library needed for the function is not linked.
In this case:
XInputGetState() requires XInputLib.lib and Xinput9_1_0.lib.
This can be resolved by adding the libraries in the project settings or via:
#pragma comment(lib,"XInput.lib")
#pragma comment(lib,"Xinput9_1_0.lib")

Visual C++ versus standard c++

1) I have been working with standard C++ (CodeBLocks)and starting to move to Visual C++. When creating a console application the VS builds the following:
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
This is not the standard c++ syntax but windows version.
Now, is there a way to use the standard c++ syntax in Visual Studio C++ and avoid the above
sintax so as to use the standard?
I mean, using VS C++ be able to code something standard such as:
#include "<iostream.h>"
#include <stdlib.h>
int main()
{
int month, day, year;
cout << "Hellow World" << endl;
return 0;
}
2) I get in visual c++ error by trying to include very common libraries such as
#include "<iostream.h>". Any advise much appreciated. (using VS 2013 and comparing it with previous code in WnDEv).
3) I also attemted to use this with an empty project adding:
but when I build it InteliSense cannot open source file stdafx.h, IntelliSense identifier "cout" is undefined, IntelliSense identifier "cin" is undefined. Please help. thank you
#include "stdafx.h"
#include<iostream>
#include<conio.h>
void main()
{
//clrscr();
int number, count = 0;
cout << "ENTER NUMBER TO CHECK IT IS PRIME OR NOT ";
cin >> number;
for (int a = 1; a <= number; a++)
{
if (number%a == 0)
{
count++;
}
}
if (count == 2)
{
cout << " PRIME NUMBER \n";
}
else
{
cout << " NOT A PRIME NUMBER \n";
}
//getch();
}
The inclusion of "stdafx.h" is because Visual C++ by default uses pre-compiled headers, and for that to work the first non-comment line in the source file have to be that inclusion.
For the _tmain function, it tells me you have opted to make a WIN32 console project. You can make an empty project, and add files manually as needed, and use only standard C++ features, like having the proper main function instead.

how to convert mpf_class to String

Hello and sorry for my basic English. I'm trying to convert from mpf_class to a String. I know there is a function (get_str()) but it show me only digits and its exponent separated. I want to get the whole expression in a string. I tried using ostreamstring and it work but I want to know if there is another way to do that. Let me know if I made myself clear.
Basically what I did was:
std::ostringstream show;
mpf_class result, Afact,Bfact,Cfact;
result=Afact*Bfact/Cfact;
show << result;
ui->lineEdit_5->setText(QString::fromStdString(show.str()));
As you can see, I'm working in a QT project and I need to show the result in a QLineEdit and with ostreamstring it works. I just was wondering if there is a gmp function to do that. thanks
Not sure whether this can help you, but you can actually print an mpf_class object and use I/O manipulators on it as a typical float object.
Here is my code
#include <gmpxx.h>
#include <iostream>
#include <iomanip>
int main(void) {
mpf_class a;
a = 3141592653589793.2;
std::cout << a << std::endl;
// Outputs 3.14159e+15
std::cout << std::uppercase << std::showpos << std::setprecision(3) << a << std::endl;
// Outputs +3.14E+15
}
Then you can use an std::ostringstream object instead of std::cout.
Reference: https://gmplib.org/manual/C_002b_002b-Formatted-Output.html

why do I get the out of date message in visual c++ 2010 express

So I'm starting a book called " Beginning c++ Through Game Programming, third edition, by Michael Dawson" and the very fist program I tried to run didn't work. I even tried just using the source code. Here it is:
// Game Over
// A first C++ program
#include <iostream>
int main()
{
std::cout << "Game Over!" << std::endl;
return 0;
}
If this is what you see, just check the checkbox at the bottom and hit "Yes". That will keep it from popping up. It's not an error in your code.
Otherwise, you need to post the error message you are receiving.
Based on various comments I'd made for the default of pre-compiled headers under VC++ and to leave the window open until enter is pressed use the following:
#include "stdafx.h"
#include <iostream>
int main()
{
std::cout << "Game Over!" << std::endl;
cin.ignore();
return 0;
}

Resources