Debug Assertion Failed: _CrtIsValidHeapPointer(pUserData) - c++

Sometimes I get this "Debug Assertion Failed" error running my Qt project in debug mode (image).
I don't know where I wrong because the compiler says nothing and I don't know what to do to find my error.
I program under Windows Vista, using Qt Creator 2.4.1, Qt 4.8.1.
My program has to read some informations from a laser device and save them into a file with a code similar to this:
void runFunction()
{
configure_Scanning(...);
while(...)
{
// do something
scanFunction();
// do something
}
}
and this is my "incriminated" function (where I think the problem is)
void scanFunction()
{
file.open();
data = getDataFromDevice();
if(flag)
{
if(QString::compare(lineB,"")!=0)
{
QTextStream out(&file);
out << lineB << endl;
lineB = "";
}
lineA.append(data+"\t");
}
else
{
if(QString::compare(lineA,"")!=0)
{
QTextStream out(&file);
out << lineA << endl;
lineA = "";
}
lineB.prepend(data+"\t");
}
file.close();
}
Where lineA and lineB are initially two void QString: the idea is that I make a bidirectional scanning to save informations in a 2D matrix (from -X to +X and viceversa, while Y goes to a specified target). lineA memorizes the (-)to(+) reading; lineB memorizes the (+)to(-) reading. When the scanning direction changes, I write lineA (or lineB) to the file and I proceed with the scanning.
Do you understand what I said?
Could you suggest me a solution?
Thanks and sorry for my English :P

_CrtIsValidHeapPointerUserData means, that you have a heap corruption, which is noticed by debug heap checker. Suspect everybody who can write any information into any deleted dynamic object.
And yes, you'll receive heap corruction not immideately on rewrite occurs, but on the next heap check, which will be performed on any next memory allocation/deallocation. However should be simply tracked by a call stack in single threaded applications.

In our case, the program worked perfectly in DEBUG mode and crashed with the similar error trace in RELEASE mode.
In my case, the RELEASE mode was having msvscrtd.dll in the linker definition. We removed it and the issue resolved.
Alternatively, adding /NODEFAULTLIB to the linker command line arguments also resolved the issue.

Related

Eclipse CDT and Visual Studio Code have different i/o behavior with the same code why is this? [duplicate]

Good morning,
I have a problem with Eclipse IDE for C/C++ Developers.
I'm writting a smal tool for converting Strings. While testing on some point eclipse stopped to give console output.
e.g.:
cout<<"test";
doesn't get displayed.
But it's not every where... another example:
// File path as argument
int main(int argc, char* argv[]) {
if (argc != 2) {
cout
<< "ERROR: Wrong amount of arguments! Only one allowed...\n";
cout << "\n" << "Programm closed...\n\n";
exit(1);
}
CommandConverter a(argv[1]);
cout<<"test";
a.getCommandsFromCSV();
cout<<"test2";
return 0;
}
The error message is displayed correctly if the argument is missing.
But if the argument is there and the program continues the test outputs:
cout<<"test";
cout<<"test2";
are not displayed...
I am missing something obvious?
Thanks in advance!
You need to end output strings with newline, e.g.: `cout << "test\n"``. The reason is that the standard output is buffered and the buffer is flushed on newline. There probably exists a way to flush the cout buffer without outputting a newline, but I don't know it by heart. Probably includes access to the underlying streambuf (via the rdbuf method).
For me installing the 32 bit versions of Eclipse (Indigo 3.7) and the 32 bit Java JDK/JRE did not work. I use the much quicker solution from the Eclipse CDT/User/FAQ:
Quote from Eclipse CDT/User/FAQ - Eclipse console does not show output on Windows:
Eclipse console does not show output on Windows In Eclipse CDT on
Windows, standard output of the program being run or debugged is fully
buffered, because it is not connected to a Windwos console, but to a
pipe. See bug 173732 for more details. Either add fflush calls after
every printf or add the following lines in the start of the main
function:
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
I had a similar problem. In my case the program would give output if run from the command line but not from eclipse console. The solution was to use the 32 bit version of eclipse and not the 64 bit one.
I read that it was a bug. Might not be the same issue though.
I was also searching for exactly this information when I found this on the Microsoft website
http://support.microsoft.com/kb/94227
I think a simple method is to use std::flush when you want to force flushing the internal buffer that cout uses
*std::cout << ... << std::flush;*
This Happens when you debug your code and dont see the output till the last.
use
cout<<"what ever overloads"<< flush;
to see the output immediately on stdout(console)
Hi after some similar struggle I figured out, that the first element of the project's properties environment PATH variable must be "C:\MinGW\bin;" Otherwise a wrong version might be used, especially if you use different compiler.
try outputting a space at the beginning of each line
cout << " " << .....

getline unreliable on macOS?

as a school project I have to code a video game with SDL2, imgui and SFML and I'm facing a really weird problem :
getline seems unreliable on macOS but not on linux
Let me explain, when I compile and run my code, I am able to read my configuration file properly and display the data on screen : it is working everytime on my linux computer but on my macbook it is working like 1 time out of 5.
My configuration file :configuration file
how the information is supposed to be displayed (working properly on linux but not everytime on macOS) : how it is when it works
The code :
// Récupération des derniers paramètres
std::ifstream fichierSauvegardeR ("data/save.txt");
if (fichierSauvegardeR.is_open())
{
getline(fichierSauvegardeR, strNbDes);
strcpy(buf_nb_des, strNbDes.c_str());
getline(fichierSauvegardeR, strNbJoueurs);
strcpy(buf_nb_joueurs, strNbJoueurs.c_str());
// getline(fichierSauvegardeR, strNomJoueur);
// strcpy(noms_joueurs[0], strNomJoueur.c_str());
for (int i = 0; i < nbJoueurs; i++) {
if(!getline(fichierSauvegardeR, strNomJoueur))
{
break;
}
else
{
strcpy(noms_joueurs[i], strNomJoueur.c_str());
}
}
fichierSauvegardeR.close();
}
Note that, the first 2 lines of the configuration file are always properly read (even on macOS), what doesn't work is the other lines (I've tried replacing the "\n" by std::endl and it didn't changed anything)
Without responding to your answer (i don't have a mac for testing). I see that you use many C features. I recommend you to use "istringstream" to parse your file.
Something like this: https://stackoverflow.com/a/9551101/12374897

How to check if a program exists in path using Qt?

I have this code:
QProcess* proceso = new QProcess();
QString programa = "unknow -v";
proceso->start(programa);
proceso->waitForFinished();
QString normal = proceso->readAllStandardOutput();
QString errores = proceso->readAllStandardError();
qDebug() << normal;
qDebug() << errores;
The output I get is:
""
""
But I want get and error that says: Command not found.
Thanks in advance.
EDITED:
I found this solution using Qt:
int result = system("unknow -v");
if(result!=0) {
qDebug() << "No está instalado nasm";
} else {
qDebug() << "Está instalado.";
}
But I want get an output into a QString.
You could fetch the value of your PATH using getenv("PATH") then split it on colons (or semi-colons for Windows), iterate on every directory there, test that it contains a unknow file, etc....
So you don't need any Qt thing for that. Just plain C++ (string operations).
(this is not bullet-proof: some other process might modify a directory in your $PATH between such a test and the actual start of process; but it should often be enough in practice)
On POSIX systems, you might run your command thru sh -c (e.g. run sh -c 'unknow -v'), but be careful of escapes and code injections (so check the string unknow -v for things like single and double quotes, etc...)
You could also use popen(3) perhaps using which but I don't recommend that (too complex).
I am not sure it is worth the trouble anyway. Why don't you simply just run the program.... I don't see much difference between a missing executable and a command failing for many other reasons.
Please try this:
QProcess program;
QString commandToStart= "unknown -v";
QStringList environment = program.systemEnvironment();
program.start(commandToStart);
bool started = program.waitForStarted();
if (!program.waitForFinished(10000)) // 10 Second timeout
program.kill();
int exitCode = program.exitCode();
QString stdOutput = QString::fromLocal8Bit(program.readAllStandardOutput());
QString stdError = QString::fromLocal8Bit(program.readAllStandardError());
If started is true, the program could be started. That usually means, it was in the path. If it's false, check whether the path in environment is correct.
The exitCode is only helpful, if the process could actually be started and something else went wrong. If the program could not be started at all, exitCode will be 0 and stdOutput and stdError will be empty! That may be misleading.
The question is about if you are able to run the command aka if the command exists on your system. This means NOT trying to launch it and see what happens, huge difference!
How about this?
I like the idea of which but it won't work under Windows, AFAIK.
QProcess findProcess;
QStringList arguments;
arguments << myCommand;
findProcess.start("which", arguments);
findProcess.setReadChannel(QProcess::ProcessChannel::StandardOutput);
if(!findProcess.waitForFinished())
return false; // Not found or which does not work
QString retStr(findProcess.readAll());
retStr = retStr.trimmed();
QFile file(retStr);
QFileInfo check_file(file);
if (check_file.exists() && check_file.isFile())
return true; // Found!
else
return false; // Not found!

Ifstream.open() fails after a couple iterations

I'm new the Ubuntu enviornment and I've also never used eclipse before.
So I'm trying to do a very simple task of just opening a file to read. I developed this on my mac in xcode and it works but when I put it through eclipse it fails.
I am calling this function continuously in order to simulate a state change like if someone pressed a button. The code is:
int event = 0;
ifstream inFile;
inFile.open("StatusFiles/currentEvent.txt"); //Crashes here after a couple times
if(inFile)
{
inFile >> event;
inFile.close();
}
else
{
cout << "StatusFiles/currentEvent.txt Not Found" << endl;
}
Very simple and the code is very common in order to open files in C++. There isn't a permission issues and I've included all the libraries I needed and I have the correct path.
I can read from the file a few times, but after two or three reads when i call this function, the code fails
The line it fails on line #2 is when I try to open the file. Eclipse yells at me saying:
No source available for "std::basic_ifstream>::open() at 0xb8f83982
This literally makes no sense to me and I would very much like some help!
--
Thanks

Make main() "uncrashable"

I want to program a daemon-manager that takes care that all daemons are running, like so (simplified pseudocode):
void watchMe(filename)
{
while (true)
{
system(filename); //freezes as long as filename runs
//oh, filename must be crashed. Nevermind, will be restarted
}
}
int main()
{
_beginThread(watchMe, "foo.exe");
_beginThread(watchMe, "bar.exe");
}
This part is already working - but now I am facing the problem that when an observed application - say foo.exe - crashes, the corresponding system-call freezes until I confirm this beautiful message box:
This makes the daemon useless.
What I think might be a solution is to make the main() of the observed programs (which I control) "uncrashable" so they are shutting down gracefully without showing this ugly message box.
Like so:
try
{
char *p = NULL;
*p = 123; //nice null pointer exception
}
catch (...)
{
cout << "Caught Exception. Terminating gracefully" << endl;
return 0;
}
But this doesn't work as it still produces this error message:
("Untreated exception ... Write access violation ...")
I've tried SetUnhandledExceptionFilter and all other stuff, but without effect.
Any help would be highly appreciated.
Greets
This seems more like a SEH exception than a C++ exception, and needs to be handled differently, try the following code:
__try
{
char *p = NULL;
*p = 123; //nice null pointer exception
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{
cout << "Caught Exception. Terminating gracefully" << endl;
return 0;
}
But thats a remedy and not a cure, you might have better luck running the processes within a sandbox.
You can change the /EHsc to /EHa flag in your compiler command line (Properties/ C/C++ / Code Generation/ Enable C++ exceptions).
See this for a similar question on SO.
You can run the watched process a-synchronously, and use kernel objects to communicate with it. For instance, you can:
Create a named event.
Start the target process.
Wait on the created event
In the target process, when the crash is encountered, open the named event, and set it.
This way, your monitor will continue to run as soon as the crash is encountered in the watched process, even if the watched process has not ended yet.
BTW, you might be able to control the appearance of the first error message using drwtsn32 (or whatever is used in Win7), and I'm not sure, but the second error message might only appear in debug builds. Building in release mode might make it easier for you, though the most important thing, IMHO, is solving the cause of the crashes in the first place - which will be easier in debug builds.
I did this a long time ago (in the 90s, on NT4). I don't expect the principles to have changed.
The basic approach is once you have started the process to inject a DLL that duplicates the functionality of UnhandledExceptionFilter() from KERNEL32.DLL. Rummaging around my old code, I see that I patched GetProcAddress, LoadLibraryA, LoadLibraryW, LoadLibraryExA, LoadLibraryExW and UnhandledExceptionFilter.
The hooking of the LoadLibrary* functions dealt with making sure the patching was present for all modules. The revised GetProcAddress had provide addresses of the patched versions of the functions rather than the KERNEL32.DLL versions.
And, of course, the UnhandledExceptionFilter() replacement does what you want. For example, start a just in time debugger to take a process dump (core dumps are implemented in user mode on NT and successors) and then kill the process.
My implementation had the patched functions implemented with __declspec(naked), and dealt with all the registered by hand because the compiler can destroy the contents of some registers that callers from assembly might not expect to be destroyed.
Of course there was a bunch more detail, but that is the essential outline.