C++, Qt4 - QLabel.setText() seemingly causes segmentation fault - c++

EDIT: PROBLEM SOLVED, see my answer. TL;DR: wasn't related to Qt, I made a stupid mistake with array (std::vector) ranges.
Using Windows7, Qt version 4.8.7, x86_64-w64-mingw32-g++ as compiler, Cygwin for compiling, Notepad++ for editing. (The same project has Flex and Bisonc++ in it as well, but those are not related to the issue and work fine.)
I have an std::vector< QLabel* >, and I attempt to fill it with data. In one test case (which is the QFrame containing the vector getting the data from the main function with no involvement from other classes) this works out fine, as expected.
In another case, when using a QMainWindow to trigger it's own slot-method which calls for the same function, it runs into a segmentation fault at the QLabel.setText( QString::number() ) part.
ui_parts.h
#ifndef UI_PARTS_H_INCLUDED
#define UI_PARTS_H_INCLUDED
#include <QWidget>
#include <QLabel>
#include <QGridLayout>
#include <QFrame>
#include <vector>
#include <string>
class regDisplay : public QFrame{
Q_OBJECT
public:
regDisplay(int _meret, const std::string &nev, QWidget *parent = 0);
~regDisplay() {}; // not actually in the header, here for compression
int size() const { return meret; };
void setValues(const std::vector<AP_UC> &val);
private:
QGridLayout* gridLayout;
int meret;
std::vector<unsigned char> valueVec;
std::vector<QLabel*> valueLabel;
};
#endif // UI_PARTS_H_INCLUDED
ui_parts.cpp
#include <iostream>
#include "ui_parts.h"
using namespace std;
regDisplay::regDisplay(int _meret, const std::string &nev, QWidget *parent)
: QFrame(parent), name(nev), meret(_meret){
valueVec.resize(meret, 0);
valueLabel.resize(meret, NULL);
gridLayout = new QGridLayout(this);
// [...] setting up other properties of the widget
for (int i = 0; i < meret; ++i){
valueLabel[i] = new QLabel(this);
// [...] set properties for valueLabel[i]
gridLayout -> addWidget( valueLabel[i], 1, i);
}
}
// the following function which is suspected with causing the segfault
void regDisplay::setValues(const std::vector<AP_UC> &val){
for (int i = 0; i < meret; ++i)
{
valueVec[i] = val[i];
cout << (int)valueVec[i] << "\t" << (QString::number( (int)valueVec[i] )).toStdString() << endl;
cout << "ptr: " << (valueLabel[i]) << endl;
if ( valueLabel[i] == NULL ){
cout << "NULL POINTER? WTF " << i << endl;
} else{
cout << "not null pointer " << i << endl;
}
cout << "kek" << endl;
valueLabel[i] -> setText( QString::number( (int)valueVec[i] )); // SEGFAULT
cout << i << "+" << endl;
}
}
Calling the function:
vector<unsigned char> vecUC(4);
allapot.get_reg("eax", vecUC); // I'm 100% sure this works correctly, tested thoroughly
// it makes vecUC equal to an std::vector<unsigned char> which is 4 long
eax -> setValues( vecUC ); // regDisplay* eax;
// initialized: eax = new regDisplay(4, "eax", this ); in the constructor of this class (which inherits from QMainWindow)
Console output of this piece of code:
0 0
ptr: 0x32f160
not null pointer 0
kek
Segmentation fault
My read on this:
valueVec[i] and its QString version are both 0 (the argument of setText() seems to be fine)
valueLabel[i] has a pointer value which isn't 0, initialized as such in the constructor
valueLabel[i] is not a nullpointer (i == 0 in this case)
the first cout before the setText() works, the second does not
Removing (commenting) the setText() calls from throughout the code make it work properly (but I need some way of putting out text on the UI, so they're needed in some form for the purpose of the program).
'make ui_vec' creates the testing module for the regDisplay and veremDisplay classes, which works fine
'make ui_main' creates the testing module for mainDisplay, which causes the issues to arise
I do not know what causes the issue and I'd appreciate any help with removing it. Thank you in advance.
Update (16.05.14):
I recreated the entire project in wxWidgets, and it worked fairly similarly, but at basically the same point it also started throwing segfaults around. It appears to happen randomly, sometimes the entire program works correctly, sometimes on the first action it fails.
However, running the program through gdb completely solved the issue, I haven't encountered any segfaults.
Update (16.05.16):
After some further testing, it appears that the problem is somewhere in the bisonc++ / flex parser I created. There is one piece of code using it that works completely fine every time, and if I try to add to it (going back with an std::stack to previous states; using a class to navigate) it segfaults after the second instruction (the first works fine).
Footnotes:
Link for repository - the problem is in src/cpp/ui_parts.cpp line79 (regDisplay::setValues()), called from mainDisplay::displayAllapot() (src/cpp/ui_main.cpp line195). Debug messages might have changed a bit, rest of the code is the same.
Most of the documentation and commments are in Hungarian and not in English, my apologies for that.
Another (probably related issue): the very same program sometimes runs into the same segmentation fault at different locations - sometimes the regDisplay::setValues() works fine, and the problem appears at veremDisplay::updateValues() - during a loop, maybe on the first run, maybe later, sometimes it works through the entire thing, and I haven't seen any consistency in it yet (it mostly stops working on the first run).
Third problem (again, most likely related): when calling the openFile() function, it runs properly until the end (the last instruction being a debug message and working correctly), but gives a seg-fault (this would make me think of destructor issues). However, if I connect a different function (oF2()) to the same event instead, then have oF2() call openFile() and write a debug message (and to nothing else), then the debug message shows and the segmentation fault appears afterward - and there were no local variables or parameters received, so no destructor should run between the last instruction of the code and the function terminating.

I found the issue, I went up to 10 in an std::vector that was only 7 in size (it only appeared in some test cases), fixing that solved every issue I had, no segmentation faults appeared so far in fairly extensive testing.
Since the real problem wasn't related to Qt in any way (also not to bisonc++ or flex), apart from the "check your array ranges" lesson, I don't think there is any real reason to keep this thread around. If mods see this, feel free to delete the question - if the solution isn't enough to keep it up.

I don't see in your code problem that may cause segfault.
But my guess that your compilation flags may cause such segfault.
For example, you use std::string and toStdString.
If Qt compiled with another version of compiler, or for example if you link you program statically with c++ runtime library (which you do accroding to your makefile[-static-libgcc -static-libstdc++]) and Qt links with dll variant of c++ runtime, then your program and Qt library may think that they work with the same version of std::string, but actually the work wtih different versions of std::string,
and std::string that allocated inside Qt may cause segfault, when you call
destructor of it inside your program. Or you create QFile with FILE * created by fopen, and you catch segfault in ~QFile, because of Qt FILE and your FILE are different.
So make sure, that your Qt compiled with the same compiler as your program,
and Qt builds with the same flags as your program.
Actually sizeof(std::string) and sizeof(FILE) may be the same, but can be used different allocators.

Related

C++ socketio segmentation fault in bound function

This is my first question on stackoverflow and I'm new to C++. I hope you can all forgive my ignorance to the probably obvious problem here, but I'm at a loss.
Basically, I'm just trying to catch events emitted by a nodejs server in my C++ client. I've successfully compiled my binary (imported boost and socketio) and much hardache. I'm trying to emit an event through a websocket connection, but I first need to ensure the connection is successful. I've been mostly following the tutorial at this link: https://socket.io/blog/socket-io-cpp/. I've also been following the source code, which can be found here: https://github.com/socketio/socket.io-client-cpp/tree/master/examples/QT
For some reason, I seem to be getting a segfault when I access my _io pointer in my bound function (in the onConnected function of the SocketHandler class).
I'm sure I'm doing something silly, but any help is appreciated. Maybe I'm misunderstanding the use of the std::bind function? I'm coming from a mostly javascript world.
main.cpp
#include "sockethandler.h"
int main()
{
SocketHandler sh;
}
sockethandler.cpp
#include <iostream>
#include "sockethandler.h"
const char name[13] = "raspberry_pi";
SocketHandler::SocketHandler() :
_io(new client())
{
using std::placeholders::_1;
_io->set_socket_open_listener(std::bind(&SocketHandler::OnConnected,this,_1));
_io->connect("http://127.0.0.1:3000");
_io->socket()->on("bot-command", [&](sio::event& ev) {
std::cout << "GOT IT!" << "\n";
//handle login message
//post to UI thread if any UI updating.
});
}
void SocketHandler::OnConnected(std::string const& nsp)
{
std::cout << "CONNECTED" << "\n";
// I can access a private class variable such as _a as a string
// here
_io->socket()->emit("join");
}
sockethandler.h
#ifndef SOCKETHANDLER_H
#define SOCKETHANDLER_H
#include <sio_client.h>
using namespace sio;
class SocketHandler {
public:
explicit SocketHandler();
private:
void OnConnected(std::string const& nsp);
std::unique_ptr<client> _io;
};
#endif // SOCKETHANDLER_H
Pretty sure the socket io library you are using is threaded. Your object is created, sets up the callback (which include references to itself), the constructor exits, main exits and the automatic (stack) variable sh is destroyed. Then the socket io library tries to run the callback which no longer has references to a valid object and it crashes. Put a debug statement in your SocketHandler destructor like cerr << "destructor called" << endl; and I'm pretty sure you'll always see that called before the program crashes.
To prove it to yourself, put a sleep(10); or whatever as the last line of code in your main to stall it from exiting and I'm guessing you'll see your program succeed.

C++ Visual Studio Release build unused code crash

I have a question which is quite general, but I hope someone will be able to at least point me in the right direction.
I created my project a I was building it only in Debug mode with /MDd flag.
But it started to have perfomance issues, so I wanted to try it in Release mode to see, how it goes.
Problem is, that when I use /MD or /MT flag and Release mode my application instantly crashes.
So I tried to find out why. It works fine in Debug. I've tried some code changes, but nothing helped. So I decided to make my app just start and comment out rest of my code. But it was still crashing. Even when my code was unused. It didn't crash only, when I completly removed those unused parts of code.
I think it's something with variable inicialization/declaration, but I'm not quite sure what I should look for.
Could someone suggest me what can cause application to crash even if it's just Declaration/Inicialization and is not even used in RunTime?
I hope you can somehow understand what is my problem.
Thanks for any suggestions!
EDIT: Code which crashes, when unused code is in project, but does not crash when i remove unused code.
#include "core/oxygine.h"
#include "Stage.h"
#include "DebugActor.h"
//#include "Galatex.h"
using namespace oxygine;
//called each frame
int mainloop()
{
//galatex_update();
//update our stage
//update all actors. Actor::update would be called also for all children
getStage()->update();
if (core::beginRendering())
{
Color clearColor(32, 32, 32, 255);
Rect viewport(Point(0, 0), core::getDisplaySize());
//render all actors. Actor::render would be called also for all children
getStage()->render(clearColor, viewport);
core::swapDisplayBuffers();
}
//update internal components
//all input events would be passed to Stage::instance.handleEvent
//if done is true then User requests quit from app.
bool done = core::update();
return done ? 1 : 0;
}
//it is application entry point
void run()
{
ObjectBase::__startTracingLeaks();
//initialize Oxygine's internal stuff
core::init_desc desc;
#if OXYGINE_SDL || OXYGINE_EMSCRIPTEN
//we could setup initial window size on SDL builds
desc.w = 1800;
desc.h = 1000;
//marmalade settings could be changed from emulator's menu
#endif
//galatex_preinit();
core::init(&desc);
//create Stage. Stage is a root node
Stage::instance = new Stage(true);
Point size = core::getDisplaySize();
getStage()->setSize(size);
//DebugActor is a helper actor node. It shows FPS, memory usage and other useful stuff
DebugActor::show();
//initialize this example stuff. see example.cpp
//galatex_init();
#ifdef EMSCRIPTEN
/*
if you build for Emscripten mainloop would be called automatically outside.
see emscripten_set_main_loop below
*/
return;
#endif
//here is main game loop
while (1)
{
int done = mainloop();
if (done)
break;
}
//user wants to leave application...
//lets dump all created objects into log
//all created and not freed resources would be displayed
ObjectBase::dumpCreatedObjects();
//lets cleanup everything right now and call ObjectBase::dumpObjects() again
//we need to free all allocated resources and delete all created actors
//all actors/sprites are smart pointer objects and actually you don't need it remove them by hands
//but now we want delete it by hands
//check example.cpp
//galatex_destroy();
//renderer.cleanup();
/**releases all internal components and Stage*/
core::release();
//dump list should be empty now
//we deleted everything and could be sure that there aren't any memory leaks
ObjectBase::dumpCreatedObjects();
ObjectBase::__stopTracingLeaks();
//end
}
#ifdef __S3E__
int main(int argc, char* argv[])
{
run();
return 0;
}
#endif
#ifdef OXYGINE_SDL
#include "SDL_main.h"
extern "C"
{
int main(int argc, char* argv[])
{
run();
return 0;
}
};
#endif
#ifdef EMSCRIPTEN
#include <emscripten.h>
void one() { mainloop(); }
int main(int argc, char* argv[])
{
run();
emscripten_set_main_loop(one, 0, 0);
return 0;
}
#endif
So I'll write it here for possibly other newbies like me which would find themselves in similar sutiation.
My problem was in Initialization of static and other variables which were "outside of function". For example:
MyObject object = new MyObject(); //This was the reason, why it was crashing, just had to move
// initialization of such variables to function which was called with object creation.
void MyClass::myFunction(){
object->doSomething();
}
So when program started inicialization of those variables caused crash of program.
Note: It seems like it was problem with objects, cause variables like Integers or such were just fine.
Well, I'm not totally sure why this is allowed in Debug mode, but crashes Release mode right after start, maybe someone could answer under this comment and explain this behavior, I'm just begginer and I'm doing lot of bad stuff, but I'm trying and that's good, right? :D
I hope i didn't waste too much of your time guys and maybe this post will be useful to someone in future.

A buffer overrun has occurred

A few days ago, my company changed our operation system from Windows XP to Windows 7 (32-bit) for security matters.
I use C++ in VS 2008, QT 4.8.1, and Boost. Struct Member Alignment in my application is 1 byte (/Zp1).
After the change, I found one bug:
I load the library I made with QPluginLoader and then I use qobject_cast to cast it to my interface. In my library I might load another.
When I test my application on Debug mode after the operating system changed, it was all OK. Everything was working like it suppose to, then I changed it to Release and my application started crashing.
When I debugged it with VS 2008, I saw this error:
A buffer overrun has occurred in my_app.exe which has corrupted the program's internal state. Press Break to debug the program or Continue to terminate the program.
For more details please see Help topic 'How to debug Buffer Overrun Issues'.
The application still work fine on Windows XP (Release and Debug mode).
At the beginning, I thought it was because of a dependency or something I missed. After a couple of hours testing and tracing my application with logging in Release mode, I finally found out what was wrong. My application crashes when one method tries to return a value (anything) to another that called it inside the library.
For example:
Method B return Bool and I call it in Method A. When Method B is finished and ready to return a Bool value to Method A, wy application crashes. It also crashes when it wants to return to the method that loaded the library, if the method returns a value. Somehow, it's ok with a method that don't return any value (void).
To be sure what is wrong exactly, the code inside my methods, I made another application (tester) and started to add my code part-by-part to find the error. I believe it has something to do with QT.
Please check the following code and tell me if you know what is wrong.
I have main.cpp that loads a plugin like this:
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString filename = "correct path";
QPluginLoader* pluginLoader = new QPluginLoader(filename);
QObject *plugin = pluginLoader->instance();
PluginInterface* plugin_instance;
if (plugin)
{
SecureZeroMemory(&plugin_instance, sizeof(PluginInterface));
plugin_instance = qobject_cast<PluginInterface *>(plugin);
}
bool result = plugin_instance->initialize();
return a.exec();
}
This is my interface:
class PluginInterface
{
public:
virtual bool initialize() = 0;
};
QT_BEGIN_NAMESPACE
Q_DECLARE_INTERFACE(PluginInterface,"some text");
QT_END_NAMESPACE
I make my library like this:
plugin.hpp
class Plugin : public QObject, public PluginInterface
{
Q_OBJECT
Q_INTERFACES(PluginInterface)
public:
Plugin();
bool initialize();
};
plugin.cpp
#define SUPPORTED_VERSIONS 0x01011403
#define WFS_TRACE_NONE 0
bool Plugin::initialize()
{
WFSVERSION wfs_version;
HRESULT hRes;
cout << "WFSStartUp" << endl;
hRes = WFSStartUp(SUPPORTED_VERSIONS, &wfs_version);
WORD version = wfs_version.wVersion;
cout << "version : " << version << endl;
DWORD dwTrace = WFS_TRACE_NONE;
cout << "WFSCreateAppHandle" << endl;
HRESULT hRes2;
HANDLE app_handle;
hRes2 = WFSCreateAppHandle(&app_handle);
cout << "Result : " << hRes2 << endl;
return true;
}
Q_EXPORT_PLUGIN2(my_plugin, Plugin);
This is the output of my tester application:
WFSStartUp
version : 63424
WFSCreateAppHandle
Result : 0
Application Crash!!
The code inside Plugin::initialize() works fine. I copy/paste it to main() and ran the application to be sure about it.
What is wrong here? What am I missing?
This code:
PluginInterface* plugin_instance;
if (plugin)
{
SecureZeroMemory(&plugin_instance, sizeof(PluginInterface));
plugin_instance = qobject_cast<PluginInterface *>(plugin);
}
would be very much crash-inducing if SecureZeroMemory does what its name says it does.
To zero a pointer just set it to 0.
But, to mention also that, that would be meaningless when the next thing you do is to assign to it, as above.
I already tested without SecureZeroMemory and it still crash, SecureZeroMemery its not the cause of the crash!
Quite probably there are other bugs like that in other places in the code - places that you don't show.
At the very least, are you compiling everything in your application (all libraries, DLLs, etc.) with the same compiler, and using same settings? If you use "/Zp1", you must use it for every piece of code, including Qt itself. Such compiler flags make the code compiled with them binary incompatible with code compiled without them.
Besides, "/Zp1" is a performance killer. If you want to pack structures for dumping them to disk etc., you're going about it the wrong way. The structure that you use shouldn't be packed. Only when you're copying it to/from disk should you have another structure defined internally that is packed, and you first copy the data from unpacked to packed structure, and only then dump to disk. You're supposed to pack individual structures by using proper pragmas/attributes, not everything!
I had to change few Visual Studio build options to fix this problem!
Optimization = Custom (Configuration Properties -> C/C++ ->
Optimization)
Inline Function Expansion = Default (Configuration
Properties -> C/C++ -> Optimization)

What can go wrong if cout.rdbuf() is used to switch buffer and never set it back?

The author presented this code under the title A bus error on my platform
#include <fstream>
#include <iostream>
int main()
{
std::ofstream log("oops.log");
std::cout.rdbuf(log.rdbuf());
std::cout << "Oops!\n";
return 0;
}
The string "Oops!\n" is printed to the file "oops.log". The code doesn't restore cout's streambuf, but VS2010 didn't report a runtime error.
Since log and std::cout share a buffer, that buffer will probably be freed twice (once when log goes out of scope, then once more when the program terminates).
This results in undefined behavior, so it's hard to tell the exact reason why it triggers a bus error on his machine but silently fails on yours.
Since the other answers don't mention what to do about this I'll provide that here. You need to save and restore the buffer that cout is supposed to be managing. For example:
#include <fstream>
#include <iostream>
// RAII method of restoring a buffer
struct buffer_restorer {
std::ios &m_s;
std::streambuf *m_buf;
buffer_restorer(std::ios &s, std::streambuf *buf) : m_s(s), m_buf(buf) {}
~buffer_restorer() { m_s.rdbuf(m_buf); }
};
int main()
{
std::ofstream log("oops.log");
buffer_restorer r(std::cout, std::cout.rdbuf(log.rdbuf()));
std::cout << "Oops!\n";
return 0;
}
Now when cout's buffer is replaced before cout is destroyed at the end of the program, so when cout destroys its buffer the correct thing happens.
For simply redirecting standard io generally the environment already has the ability to do that for you (e.g., io redirection in the shell). Rather than the above code I'd probably simply run the program as:
yourprogram > oops.log
Also one thing to remember is that std::cout is a global variable with all the same downsides as other global variables. Instead of modifying it or even using it you may prefer to use the usual techniques to avoid global variables all together. For example you might pass a std::ostream &log_output parameter around and use that instead of having code use cout directly.
Your program has Undefined Behavior.
The destructor of the global cout object will delete the stream buffer when going out of scope, and the same is true of log, which also owns that very same stream buffer. Thus, you are deleting the same object twice.
When a program has Undefined Behavior, anything could happen, from formatting your hard drive to terminating without any error.
On my platform, for instance, the program enters an infinite loop after returning from main().

Function causes no errors, yet it won't return to the program

I have this very annoying issue, whenever i call a function:
void renderGame::renderMovingBlock(movingBlock* blockToRender){
sf::Shape blockPolygon;
sf::Shape blockLine = sf::Shape::Line(blockToRender->getLineBegin().x,blockToRender->getLineBegin().y,blockToRender->getLineEnd().x,blockToRender->getLineEnd().y, 3.f,movingBlockLineColor);
for(auto i = blockToRender->getVertexArray()->begin(); i!=blockToRender->getVertexArray()->end(); ++i){
blockPolygon.AddPoint(i->x, i->y, movingBlockBlockColor);
}
renderToWindow->Draw(blockLine);
renderToWindow->Draw(blockPolygon);
}
Which is a simple function, it takes a pointer to an object and uses SFML to render it on the screen. It's a simple polygon that moves on a rail.
getVertexArray() returns a pointer to the object's vector of vertices, renderToWindow is a pointer to sf::RenderWindow
The very weird issue i have is that i can call this function it won't return from it, VC++ breaks and points me to:
int __cdecl atexit (
_PVFV func
)
{
return (_onexit((_onexit_t)func) == NULL) ? -1 : 0;
}
I'm getting weird behavoir here, i can stop this function right before exiting by calling the Display() function and system("pause"), it'll display everything perfectly fine, but one step further and it breaks.
I'll add that i'm sending a dynamically allocated object, when i set a regular one everything's fine. It's weird, when i debug the program then the polygon and line have the right coordinates, everything displays properly, but it just can't return from the function.
If a function will not return sounds like you messed up the stack somewhere previously - this is most likely an out-of-bounds write.
Or possibly because you are ending up in atexit there could have been an uncaught exception thrown.
Either way - welcome to the joys of programming - now you have to find an error which probably happens long before your function gets stuck
You could try some tools like valgrind (if its available for windows) or some other bounds checkers.