C++ - Empty method causing SIGSEV signal - c++

I'm making a simple deck/card/hand object oriented system for a university assignment, and I've become stuck on this problem.
I've set up a simple test class which calls various methods in objects.
int main() {
Deck deck = Deck();
deck.DisplayDeck();
deck.Shuffle();
deck.DisplayDeck();
Hand hand = Hand(1);
Card* card;
card = deck.DealNextCard();
hand.AddCard(card);
hand.ftring();
deck.DisplayDeck();
}
The problem comes at hand.ftring(). When I call this, it causes a segmentation fault. The weird thing is, it contains no code.
in hand.cpp:
string Hand::ftring() {
}
If I remove it, it runs to completion. If I add a console output to the method, it prints it and then crashes. I'm completely at a loss as to what to do, as the debugger only states
Program received signal SIGSEGV, Segmentation fault.
In ?? () ()

You declare that you are returning a string in ftring function, but you don't actually return anything. This is bad.

Your method must return a string - this is the way you've declared it. You're getting undefined behavior.

Related

Segmentation fault on specific memory address

I have one of the most annoying problems in my opinion, called a segmentation fault. Usually with a bit of help from gdb and tracing all my code, I manage to solve these problems. Unfortunately, not this time. Since my code is kind of complex, I will show snippets relevant to the problem.
First of all, the error is given on this setter function:
void Texture::setRenderer( SDL_Renderer* renderer ) {
m_renderer = renderer;
}
Ofcourse, in my texture class there is a variable defined as followed:
SDL_Renderer* m_renderer = nullptr;
Because of the type of error, I tried tracing the specific memory address, to see if it is valid. So, the parameter. It comes from my resource manager class, which is trying to add a texture to a map. Specific code:
bool ResourceManager::add( const std::string texture ) {
Texture* tex;
tex->setRenderer(m_renderer);
}
Ofcourse, also this variable (m_renderer) comes from a different location. My Game class.
m_resources.setRenderer(m_renderer);
This function is called immediately after I initialize the renderer, without any errors. So there my trace ends, without finding the problem...
I have also tried printing the memory address in all of these functions. They all print exactly the same memory address.
Stacktrace from gdb:
Thread 1 "ConceptGame" received signal SIGSEGV, Segmentation fault.
0x0000000000408868 in Texture::setRenderer (this=0x0, renderer=0x660b60)
at ../Texture.cpp:68
68 m_renderer = renderer;
(gdb) bt
#0 0x0000000000408868 in Texture::setRenderer (this=0x0, renderer=0x660b60)
at ../Texture.cpp:68
#1 0x0000000000406865 in ResourceManager::add (this=0x7fffffffdb50,
texture="penguin.png") at ../ResourceManager.cpp:31
#2 0x0000000000403fb1 in Game::run (this=0x7fffffffdae0) at ../Game.cpp:83
#3 0x0000000000408b5f in main (argc=1, argv=0x7fffffffdcb8) at ../main.cpp:50
Any help on fixing this problem is much appreciated...
Wow. I just solved this indeed according to AndyG's comment...
While trying to fix this I accidentally didn't initialize the pointer, thus causing this problem.
Fixed by initializing the pointer;
Texture* tex = new Texture;
tex->setRenderer(m_renderer);
Thank you.

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

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.

Segfault After Registering Callback Functions

I am registering four callback functions:
glfwSetMouseButtonCallback(procMouseButton);
glfwSetMousePosCallback(procMousePosition);
glfwSetCharCallback(procCharInput);
glfwSetKeyCallback(procKeyInput);
Each callback function looks similar to this:
void GLFWCALL procMouseButton(int button, int action) {
Input::instance().processMouseButton(button, action); // doesn't do anything yet
}
Input is a singleton:
Input& Input::instance()
{
static Input instance;
return instance;
}
After the callback functions are registered, a segfault occurs. I have narrowed down the problem to two things.
First: Excluding any of the process functions causes the segfault to disappear. For example,
// this works
glfwSetMouseButtonCallback(procMouseButton);
//glfwSetMousePosCallback(procMousePosition);
glfwSetCharCallback(procCharInput);
glfwSetKeyCallback(procKeyInput);
// this works also
glfwSetMouseButtonCallback(procMouseButton);
glfwSetMousePosCallback(procMouseButton); // exclude procMousePosition
glfwSetCharCallback(procCharInput);
glfwSetKeyCallback(procKeyInput);
Second: Segfault occurs when popping or pushing a std::vector declared here in singleton Engine:
class Engine
{
public:
static Engine& instance();
std::list<GameState*> states;
private:
Engine() {}
Engine(Engine const& copy);
Engine& operator=(Engine const& copy);
};
// either causes segfault after registering functions
Engine::instance().states.push_back(NULL);
Engine::instance().states.pop_front();
I am completely baffled. I am assuming the problem is related to static initialization order fiasco, but I have no idea how to fix it. Can anyone explain why this error is occurring?
Important notes:
If I reverse the linking order, it no longer segfaults.
I am using MinGW/GCC for compiling.
I am running single threaded.
The singletons do not have default constructors, everything is initialized by Singleton::instance().initialize();
The exact segfault call stack:
0047B487 std::__detail::_List_node_base::_M_hook(std::__detail::_List_node_base*) ()
00000000 0x00401deb in std::list >::_M_insert()
00000000 0x00401dbb in std::list >::push_back()
00401D92 Engine::pushState(GameState*) ()
00404710 StartupState::initialize() ()
00402A11 Engine::initialize() ()
00000000 0x00403f29 in main()
Without seeing the rest of your program, it's hard to say why it's segfaulting. It sounds timing-related. Here's a few things you can try:
Put breakpoints in the constructors of your Engine class, Input class, (any other involved classes,) and the callback-setting code. That will tell you if the callbacks are registering before the singletons they use construct. Note that breakpoints might throw off your program's timing, so if one class hits first, you can disable that breakpoint and rerun. Try this multiple times to check the results are consistent.
Is there a reason you can't try the change to pointers instead of references (like the "fiasco" mentions)?
(Your update while I was writing this makes this part not-so-useful since the callstack shows it's not in a constructor. )This sounds like the callbacks are registering during construction of some class. If that's the case:
Can you move the registration calls so they happen under main()? That ought to get you past initializations.
Split up the class construction into two phases: the normal constructor, and an init() function. Put the critical code inside init(), and call that after everybody has finished constructing.
You could also prevent the callbacks from happening until later. If you can't move the callback registration to a later time in your game's startup, you could put flags so they don't do anything until a "safe" time. Adjusting when this flag enables could let you see "how late" is "late enough". The extra if() overhead is better than a crash. :)
volatile bool s_bCallbackSafe = false; // set this at some point in your game/app
void GLFWCALL procMouseButton(int button, int action) {
if (s_bCallbackSafe)
Input::instance().processMouseButton(button, action); // doesn't do anything yet
}

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.

Trouble tracking down a Bus Error/Seg Fault in C++ and Linux

I have a program that processes neural spike data that is broadcast in UDP packets on a local network.
My current program has two threads a UI thread and a worker thread. The worker thread simply listens for data packets, parses them and makes them available to the UI thread for display and processing. My current implementation works just fine. However for a variety of reasons I'm trying to re-write the program in C++ using an Object Oriented approach.
The current working program initialized the 2nd thread with:
pthread_t netThread;
net = NetCom::initUdpRx(host,port);
pthread_create(&netThread, NULL, getNetSpike, (void *)NULL);
Here is the getNetSpike function that is called by the new thread:
void *getNetSpike(void *ptr){
while(true)
{
spike_net_t s;
NetCom::rxSpike(net, &s);
spikeBuff[writeIdx] = s;
writeIdx = incrementIdx(writeIdx);
nSpikes+=1;
totalSpikesRead++;
}
}
Now in my new OO version of the program I setup the 2nd thread in much the same way:
void SpikePlot::initNetworkRxThread(){
pthread_t netThread;
net = NetCom::initUdpRx(host,port);
pthread_create(&netThread, NULL, networkThreadFunc, this);
}
However, because pthead_create takes a pointer to a void function and not a pointer to an object's member method I needed to create this simple function that wraps the SpikePlot.getNetworSpikePacket() method
void *networkThreadFunc(void *ptr){
SpikePlot *sp = reinterpret_cast<SpikePlot *>(ptr);
while(true)
{
sp->getNetworkSpikePacket();
}
}
Which then calls the getNetworkSpikePacket() method:
void SpikePlot::getNetworkSpikePacket(){
spike_net_t s;
NetCom::rxSpike(net, &s);
spikeBuff[writeIdx] = s; // <--- SegFault/BusError occurs on this line
writeIdx = incrementIdx(writeIdx);
nSpikes+=1;
totalSpikesRead++;
}
The code for the two implementations is nearly identical but the 2nd implementation (OO version) crashes with a SegFault or BusError after the first packet that is read. Using printf I've narrowed down which line is causing the error:
spikeBuff[writeIdx] = s;
and for the life of me I can't figure out why its causing my program to crash.
What am I doing wrong here?
Update:
I define spikeBuff as a private member of the class:
class SpikePlot{
private:
static int const MAX_SPIKE_BUFF_SIZE = 50;
spike_net_t spikeBuff[MAX_SPIKE_BUFF_SIZE];
....
}
Then in the SpikePlot constructor I call:
bzero(&spikeBuff, sizeof(spikeBuff));
and set:
writeIdx =0;
Update 2: Ok something really weird is going on with my index variables. To test their sanity I changed getNetworkSpikePacket to:
void TetrodePlot::getNetworkSpikePacket(){
printf("Before:writeIdx:%d nspikes:%d totSpike:%d\n", writeIdx, nSpikes, totalSpikesRead);
spike_net_t s;
NetCom::rxSpike(net, &s);
// spikeBuff[writeIdx] = s;
writeIdx++;// = incrementIdx(writeIdx);
// if (writeIdx>=MAX_SPIKE_BUFF_SIZE)
// writeIdx = 0;
nSpikes += 1;
totalSpikesRead += 1;
printf("After:writeIdx:%d nspikes:%d totSpike:%d\n\n", writeIdx, nSpikes, totalSpikesRead);
}
And I get the following output to the console:
Before:writeIdx:0 nspikes:0 totSpike:0
After:writeIdx:1 nspikes:32763 totSpike:2053729378
Before:writeIdx:1 nspikes:32763 totSpike:2053729378
After:writeIdx:1 nspikes:0 totSpike:1
Before:writeIdx:1 nspikes:0 totSpike:1
After:writeIdx:32768 nspikes:32768 totSpike:260289889
Before:writeIdx:32768 nspikes:32768 totSpike:260289889
After:writeIdx:32768 nspikes:32768 totSpike:260289890
This method is the only method where I update their values (besides the constructor where I set them to 0). All other uses of these variables are read only.
I'm going to go on a limb here and say all your problems are caused by the zeroing out of the spike_net_t array.
In C++ you must not zero out objects with non-[insert word for 'struct-like' here] members. i.e. if you have an object that contains a complex object (a std string, a vector, etc. etc.) you cannot zero it out, as this destroys the initialization of the object done in the constructor.
This may be wrong but....
You seemed to move the wait loop logic out of the method and into the static wrapper. With nothing holding the worker thread open, perhaps that thread terminates after the first time you wait for a UDP packet, so second time around, sp in the static method now points to an instance that has left scope and been destructed?
Can you try to assert(sp) in the wrapper before trying to call its getNetworkSpikePacket()?
It looks like your reinterpret_cast might be causing some problems. When you call pthread_create, you are passing in "this" which is a SpikePlot*, but inside networkThreadFunc, you are casting it to a TetrodePlot*.
Are SpikePlot and TetrodePlot related? This isn't called out in what you've posted.
If you are allocating the spikeBuff array anywhere then make sure you are allocating sufficient storage so writeIdx is not an out-of-bounds index.
I'd also check that initNetworkRxThread is being called on an allocated instance of spikePlot object (and not on just a declared pointer).