seg fault after end of function (C++) - c++

I'm having a seg fault: 11 when I run a particular program. I feel like this problem wasn't present before I upgraded my system to Mac OS X 10.9, but it's possible I just overlooked it..
Anyway, my function looks like:
// this applies a warp to the field given, and saves output. simple!
void Apply(string warpName, string fieldName, bool conserve, string outName) {
// get lon, lat dimensions of warp
int noLongs = GetDimension(warpName, 3, "warp");
int noLats = GetDimension(warpName, 2, "warp");
int origNoLongs = noLongs, origNoLats = noLats;
// read in params
vector<double> params = ImportWarpFromNetCDF(warpName);
// rescale field to warp's dimensions, and read in
string tempName = "scaledField";
ReScale(fieldName, tempName, noLongs, noLats);
vector<vector<vector<double> > >inIntensities = ImportFieldFromNetCDF(tempName);
RemoveFile(tempName);
// just enter inIntensities for ref image, and 1 for lambda, to keep objective function happy
ObjectiveFunction objective(inIntensities, inIntensities, conserve, 1, false);
objective.setParameters(params);
// output files
ExportOutputToNetCDF(objective, outName);
cout << "BAH?!" << endl;
}
where the cout line at the end was just checking to see I'd got to the end of the function properly (which I have). Any thoughts on why this would be segfaulting here? I appreciate it might be hard to tell without seeing what the individual function calls do, and so I'll add those if necessary.
It doesn't actually matter too much, as this function is the last thing to be called (so the seg fault doesn't interrupt anything), but I still would rather get to the bottom of it!

The only thing that happens "after" the function are destructor calls. Check all your destructors of local variables. It looks like ObjectiveFunction is the only local variable that's not a primitive or standard library container, so check ObjectiveFunction::~ObjectiveFunction() for potential problems.

Related

RapidXML accessing sibling nodes causes segfaults for seemingly no reason

So I recently got a hold of RapidXML to use as a way to parse XML in my program, I have mainly been using it as a way to mess around but I have been getting some very weird issues that I'm really struggling to track down. Try and stick with me through this, because I was pretty thorough with trying to fix this issue, but I must be missing something.
First off here's the XML:
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<image key="tilemap_roguelikesheet" path="res/media/tilemaps/roguelikesheet.png" />
<image key="tilemap_tiles" path="res/media/tilemaps/tiles.png" />
</resources>
The function the segfault occurs:
void TextureManager::LoadResource(const char* pathToFile)
{
rapidxml::xml_document<>* resource = Resources::LoadResource(pathToFile);
std::string imgName;
std::string imgPath;
if (resource != NULL)
{
rapidxml::xml_node<>* resourcesNode = resource->first_node("resources");
if (resourcesNode != NULL)
{
for (rapidxml::xml_node<>* child = resourcesNode->first_node("image"); child; child = child->next_sibling())
{
//Crash here on the second loop through.
imgName = child->first_attribute("key")->value();
imgPath = child->first_attribute("path")->value();
Astraeus::Log(moduleName, "Image Name: " + imgName);
Astraeus::Log(moduleName, "Image Path: " + imgPath);
TextureManager::AddTexture(imgName, imgPath);
}
}
else
{
Astraeus::Error(moduleName, "Resources node failed to load!");
}
resource->clear();
}
else
{
std::string fileName(pathToFile);
Astraeus::Error(moduleName, fileName + " could not be loaded.");
}
}
So segfault happens on the second loop of the for loop to go through all the nodes, and triggers when it tries to do the imgName assignment. Here's where things get a bit odd. When doing a debug of the program, the initial child nodes breakdown shows it has memory pointers to the next nodes and it's elements/attributes etc. When investigating those nodes, you can see that the values exist and rapidxml has seemingly successfully parsed the file.
However, when the second loop occurs, child is shown to still have the exact same memory pointers, but this time the breakdown in values show they are essentially NULL values, so the program fails and we get the code 139. If you try and look at the previous node, that we have just come from the values are also NULL.
Now say, I comment out the line that calls on the AddTexture function, the node is able to print out all the nodes values no problems at all. (The Log method is essentially just printing to console until I do some more funky stuff with it.) so the problem must lie in the function? Here it is:
void TextureManager::AddTexture(const std::string name, const std::string path)
{
Astraeus::Log(moduleName, "Loading texture: " + path);
if (texturesLookup.find(name) != texturesLookup.end())
{
Astraeus::Error(moduleName, "Texture Key: " + name + " already exists in map!");
}
else
{
texturesLookup.insert(std::make_pair(name, path));
//Texture* texture = new Texture();
/*if (texture->LoadFromFile(path))
{
//textures.insert(std::make_pair(name, texture));
}
else
{
Astraeus::Error(moduleName, "Failed to add texture " + name + " to TextureManager!");
}*/
}
}
Ignoring the fact that strings are passed through and so should not affect the nodes in any way, this function is still a bit iffy. If I comment out everything it can work, but sometimes just crashes out again. Some of the code got commented out because instead of directly adding the key name, plus a memory pointer to a texture, I switched to storing the key and path strings, then I could just load the texture in memory later on as a workaround. This solution worked for a little bit, but sure enough began to segfault all over again.
I can't really reliably replicate or narrow down what causes the issue everytime, so would appreciate any help. Is RapidXML doc somehow going out of scope or something and being deleted?
For the record the class is practically just static along with the map that stores the texture pointers.
Thanks!
So for anybody coming back again in the future here's what was happening.
Yes, it was a scope issue but not for the xml_document as I kept initially thinking. The xml_file variable that was in the resources load function was going out of scope, which meant due to the way RapidXML stores things in memory, as soon as that goes out of scope then it frees up the memory, which led to the next time dynamic allocation happened by a specific function it would screw up the xml document and fill it with garbage data.
So I guess the best idea is to make sure xml_file and xml_document do not go out of scope. I have added some of the suggestions from previous answers, but I will point out those items WERE in the code, before being removed to help with the debug process.
Thanks everybody for the help/advice.
I'm not sure, but I think that Martin Honnen made the point.
If next_sibling() return the pointer to the text node between the two "image" elements, when you write
imgName = child->first_attribute("key")->value();
you obtain that child->first_attribute("key") is a null pointer, so the ->value() is dereferencing a null pointer. Crash!
I suppose you should get the next_sibling("image") element; something like
for (rapidxml::xml_node<>* child = resourcesNode->first_node("image");
child;
child = child->next_sibling("image"))
And to be sure not to use a null pointer, I strongly suggest you to check the attribute pointers (are you really sure that "image" elements ever carry the "key" and the "path" elements?); something like this
if ( child->first_attribute("key") )
imgName = child->first_attribute("key")->value();
else
; // do something
if ( child->first_attribute("path") )
imgPath = child->first_attribute("path")->value();
else
; // do something
p.s.: sorry for my bad English.
This line is setting my teeth on edge...
rapidxml::xml_document<>* resource = Resources::LoadResource(pathToFile);
LoadResource returns a pointer, but you never free it anywhere...?
Are you 100% sure that function isn't returning a pointer to an object that's now gone out of scope. Like this classic bug...
int * buggy()
{
int i= 42;
return &i; // UB
}
As #max66 says. You should use next_sibling("image"). If that's failing, you need to find out why.

Address of strcuture member variable changed when passed by reference

I encountered a problem when debugging my model (written in C++) in Eclipse CDT. The problem is that when I pass a structure variable, who contains various member variables such as string or vector, to a function by reference, the value of certain member variables are not updated in the scope of that function. More details are provided as below:
struct ModelConfig {
//... here are some other variables and constructors
vector<int> crop_list;
string path_to_input;
//....
};
Say now I start debugging in GDB, and here is the first function call :
void modelMain::setupModel( const ModelConfig & sim_setting ){
//... some operations to configure the model using 'sim_setting'
/* 1.3 - Initialize the land */
Set_Environment(k_farm_land, sim_setting);
// breakpoint here, printing out the value of 'sim_etting' shows 'sim_setting.path_to_input = "data/"' ; Then I enter into 'Set_Environment' function ...
//...
}
void Set_Environment(vector<Soil> & farm_land, const ModelConfig & sim_setting) {
int EXP_ID = sim_setting.EXP_ID;
string strTmp_a;
strTmp_a = sim_setting.path_to_input + "soil/parameters.txt"; // Problem is here: the GDB shows here that sim_setting.path_to_input = " ". I am expecting strTmp_a = "data/soil/parameters.txt" which now is "soil/parameters.txt" ;
//... operations for reading data
}
The sim_setting.path_to_input variable should hold the string value named data/, which is correct during the call in setupModel(...), but the value is lost (or the address is changed actually) during the call in Set_Environment(...)...
When using the GDB debug in Eclipse to trace the address of the variables, I notice that the address of sim_setting seems correct in both setupModel and Set_Environment, but the member variable of path_to_input and crop_list changed into other place, which cause the lost of data. The value of crop_list is created using .push_back().
I did not get the point since I am passing the variable by reference. The only thing that I can imagine is due to the value assignment of string and vector. Anyone have theory for this ? Thank you very much in advance !

Cocos2d-x: Crash when initiating TMXTiledMap from string

I'm having problems creating a tmx map from string input.
bool LevelManager::initLevel(int currentLevel)
{
const char* map;
try {
map = LevelManager::getLevel(currentLevel);
} catch (int) {
throw 1;
}
if(map != NULL){
CCLog("%s", map);
tileMap = CCTMXTiledMap::create(map);
tileMap->setAnchorPoint(ccp(0,0));
tileMap->setPosition(ccp(15,20));
this->addChild(tileMap, 5);
backgoundLayer = tileMap->layerNamed("Background");
} else {
throw 1;
}
return true;
}
Thats my code.
It is very unstable. Most of the times it crashes and sometimes it doesn't.
I'm loading my map from the string map. Wich is a const *char.
My map is named Level1.tmx and when i load the map like this: tileMap = CCTMXTiledMap::create("Level1.tmx"); it always works and never crashes.
And i know for a fact that the value of map is Level1.tmx because i log it in the line before the load.
When it crashes the log outputs this: (lldb)
and on the line tileMap->setAnchorPoint(ccp(0,0)); it says "Thread 1: EXC_BAD_ACCESS (code=2, adress=0x0)
Does anyone know why this happens and how to fix it?
Many thanks.
Ps: i'm using xcode, the latest cocos2d-x release and the iPhone simulator
Edit:
Using breakpoints i checked where things go bad while loading the tilemap.
on the line tileMap = CCTMXTiledMap::create(map);
my variable map is still fine
but on line tileMap->setAnchorPoint(ccp(0,0));
it is suddenly corrupted (most of the time)
It sounds like you're returning a char* string created on the stack, which means the memory may or may not be corrupted, depending on circumstances, moon phases, and what not.
So the question is: How is getLevel defined and what does it do (post the code)?
If you do something like this:
const char* LevelManager::getLevel(int level)
{
char* levelName = "default.tmx";
return levelName;
}
…then that's going to be the culprit. The levelName variable is created on the stack, no memory (on the heap) is allocated for it. The levelName variable and the memory it points to become invalid as soon as the method returns.
Hence when the method leaves this area of memory where levelName points to can be allocated by other parts of the program or other method's stack memory. Whatever is in that area of memory may still be the string, or it may be (partially) overridden by other bits and bytes.
PS: Your exception handling code is …. well it shows a lack of understanding what exception handling does, how to use it and especially when. I hope these are just remnants of trying to get to the bottom of the issue, otherwise get rid of it. I recommend reading a tutorial and introductions on C++ exception handling if you want to continue to use exceptions. Especially something like (map != NULL) should be an assertion, not an exception.
I fixed it.
const char* was to blame.
When returning my map as a char * it worked flawless.
const char *levelFileName = level.attribute("file").value();
char *levelChar = new char[strlen(levelFileName) + 1];
std:: strcpy (levelChar, levelFileName);
return levelChar;
Thats how i now return the map.

Why does the compiler not reserve enough space on the stack?

I have a C++ class Matrix22 with an array and a default constructor:
class Matrix22{
/* something more */
double mat[2][2];
Matrix22(){
for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
mat[i][j] = i==j ? 1.0 : 0.0;
}
};
I used it in my program and got a segmentation fault. As the rest was quite difficult and complicated I wrote a simple test routine, that just calls Matrix22(). No more seg fault.
I then ran gdb to debug the problem. If I call the constructor from the separate test routine, gcc reserves some memory for the member mat. I can navigate through the stack and see the return address some bytes after the array.
In the main program the compiler does not reserve enough space. The first element (mat[0][0]) gets written but any futher write just overwrites the next stack frame. I can also verify that as before the constructor the command btreturns a correct backtrace, where after the critical assignment the backtrace is corrupted.
So my question is: Why does in one case the compiler (or the linker?) reserve not enough space for the array, while in the other case that is not happening?
PS: Both "test cases" are compiled with the same compiler and flags and alsolinked against the same object files.
edit:
Here is the "simple" test case that works without seg fault:
void test_Matrix22()
{
Framework::Math::Matrix22 matrix;
}
The code with creates a seg fault is in the class ModuleShaddower (intermixed header and implementation):
class ModuleShaddower{
public:
ModuleShaddower(PVModule& module, const EnvironmentalSetup& setup, const Position& position);
private:
Matrix22 rotMatrix90;
};
ModuleShaddower::ModuleShaddower(PVModule& module, const EnvironmentalSetup& setup, const Position& position)
: module (module), position(position), setup(setup), logger(LoggerFactory::getLoggerInstance())
{
double mat[][2] = {{0, -1},{1, 0}}; // This line will never be reached
rotMatrix90 = Matrix22(mat);
}
As you see, it is quite from within the rest. I will maybe try to extract the problematic code but I think this won't help much.
If your ModuleShaddower contructor code is not getting reached (as per you code comment) then something in your constructor initialization list (related to contructuction of module, possition etc) is causing the problem.
The problem was due to the fact that two object files in different locations had the same name. In the resulting static library, that was created from that object code, sometimes the wrong file gets replaced (both were called Shaddower.o). As I renamed one of the files all went well and no more errors.
I do not know the exact origin of this problem but it is solvable like that.

Error apparently raised by not yet executed code

I'm learning c++ by writing a program to convert MIDI files to Lilypond source files.
My program is composed by two main parts:
a MIDI file parser, that creates an object called MidiFile.
a converter that takes a MidiFile objects and converts it to a Lilypond source.
Today I've started coding the converter, and while I was testing it a strange error occurred: the program dies after an exception being thrown, more specifically a HeaderError, that means that the header chunk in the MIDI file is not as expected. It wouldn't seem that strange, but this error shows up only if I add a line of code after the buggy code! I add the main() function to better explain myself
#include <iostream>
#include "midiToLyConverter.hpp"
int main(){
// a queue to store notes that have not yet been shut down
using MidiToLyConverter::Converter::NoteQueue;
// representation of a note
using MidiToLyConverter::Converter::Note;
// the converter class
using MidiToLyConverter::Converter::Converter;
// the midifile class
using Midi::MidiFile;
// representation of a midi track
using Midi::MidiTrack;
// representation of a midi event
using Midi::MidiEvents::Event;
Parser::Parser parser = Parser::Parser(); // parser class
parser.buildMidiFile(); // builds the midi file from a .mid
Midi::MidiFile* midiFile = parser.getMidiFile(); // gets the MidiFile object
// iterates over all the tracks in the MidiFile
while(midiFile->hasNext()){
std::cout<< "==========\n";
MidiTrack* track = midiFile->nextTrack();
// iterates over all events in a track
while(track->hasNext()){
Event* event = track->nextEvent();
if (event->getEventType() == Midi::MidiEvents::NOTE_ON ||
event->getEventType() == Midi::MidiEvents::NOTE_OFF
)
// print the event if it's a note on or off
event->print();
}
}
return 0;
}
With my main() like this, everything works properly, but, if I add something between buildMidiFile and the while loop, the function buildMidiFile throws the exception!!!
Even if it's a completely unrelated instruction!
#include <iostream>
#include "midiToLyConverter.hpp"
int main(){
using MidiToLyConverter::Converter::NoteQueue;
using MidiToLyConverter::Converter::Note;
using MidiToLyConverter::Converter::Converter;
using Midi::MidiFile;
using Midi::MidiTrack;
using Midi::MidiEvents::Event;
Parser::Parser parser = Parser::Parser(); // parser class
parser.buildMidiFile(); // THE EXCEPTION IS THROWN HERE
Midi::MidiFile* midiFile = parser.getMidiFile(); // gets the MidiFile object
// adding this causes the exception to be thrown by the function
// buildMidiFile() called 5 lines above!
std::vector<bool>* vec = new std::vector<bool>();
// iterates over all the tracks in the MidiFile
while(midiFile->hasNext()){
std::cout<< "==========\n";
MidiTrack* track = midiFile->nextTrack();
// iterates over all events in a track
while(track->hasNext()){
Event* event = track->nextEvent();
if (event->getEventType() == Midi::MidiEvents::NOTE_ON ||
event->getEventType() == Midi::MidiEvents::NOTE_OFF
)
// print the event if it's a note on or off
event->print();
}
}
return 0;
}
I can't explain myself how this is possible. So if anyone has ideas or advices, all the help would be greatly appreciated :) If it's helpful I can post the source code for other classes and/or functions.
Solved! As pointed out in comments to the question, it was a problem caused by some sort of memory corruption. As suggested I used a memory checher (valgrind) and found out that it was a really stupid error: i simply forgot to initialize a variable in a for loop, something like
for (int i; i < limit ; i++)
and this led to that strange error :-) Initializing i to 0 solved the problem, and now the program works with Parser object placed either on the stack or on the heap.
So I suggest others incurring in similar problems to use a memory checker to control the memory usage of their program. Using valgrind is really simple:
valgrind --leak-check=yes yourProgram arg1 arg2
where arg1 and arg2 are the (eventual) arguments that your program requires.
Furthermore compiling your program with the -g flag (at least on g++, I don't know on other compilers), valgrind will also tell you at wich line of code the memory leak occurred.
Thanks to everybody for the help!
Regards
Matteo