Error apparently raised by not yet executed code - c++

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

Related

Using an object by calling class constructor explicitly vs by default initialization + assignment operator

Considering the following example:
#include <wx/bitmap.h>
int main()
{
wxBMPHandler h;
wxImage::AddHandler(&h);
wxBitmap bm = wxBitmap(200, 200);
bm.SaveFile("file.bmp", wxBITMAP_TYPE_BMP);
return 0;
}
Since I'm only using h to call AddHandler() and not for anything else, I'd like to avoid defining it altogether and do the whole thing in one line. So I thought about replacing that with:
wxImage::AddHandler(&wxBMPHandler());
which compiles fine, but calling SaveFile() won't work then; WxWidgets will present an error stating "No image handler for type 1 defined" at runtime.
I guess the object created inside the function call is temporary, but I'm not sure about that. If not, what am I missing, and how can I avoid defining h?
It's worth noting that AddHandler() has the following signature:
static void AddHandler( wxImageHandler *handler );
[Update]
In response to M.M's comment saying:
wxImage::AddHandler(&wxBMPHandler()); should fail to compile, unless
that class has overloaded operator& for rvalues
Since I couldn't find a definition for operator& in WxWidgets' source code, I created this test project:
#include <iostream>
#include <string>
using namespace std;
string* address = nullptr;
void testing(string* input)
{
*input = "Something else entirely";
address = input;
}
int main()
{
testing(&string("Life is a test"));
cout << *address << endl;
cin.get();
return 0;
}
It compiles fine, and runs without any "hard error" - the only caveat is that nothing is shown in the screen - (*address).empty() returns true.
I even defined my own class to test with, instead of std::string and yielded the same behavior (no compiler error, no runtime error, but no output).
I also tried this one-liner, as suggested by aichao, without success:
wxImage::AddHandler(shared_ptr<wxBMPHandler>(new wxBMPHandler()).get());
I've never used wxWidgets before, but according to the wxWidgets version 3.1.1 API docs here, you should call wxImage::AddHandler using a heap-allocated handler object:
wxImage::AddHandler(new wxBMPHandler);
Therefore, there is no need for defining h. Also according to the docs, the memory for this handler object is managed by the wxWidgets framework. Specifically, the docs says that the handler is a
heap-allocated handler object which will be deleted by wxImage if it is removed later by RemoveHandler() or at program shutdown.
There is also the static member function wxImage::CleanUpHandlers() to delete all registered image handlers. According to the docs:
This function is called by wxWidgets on exit.
Therefore, you do not have to delete the handler yourself unless you specifically want to (i.e., to free up some memory).
Hope this helps.
In wxImage::AddHandler(&wxBMPHandler());, the lifetime of the temporary stop at the end of the expression, so you have dangling pointer.
In
wxBMPHandler h;
wxImage::AddHandler(&h);
wxBitmap bm = wxBitmap(200, 200);
bm.SaveFile("file.bmp", wxBITMAP_TYPE_BMP);
h outlives the call bm.SaveFile("file.bmp", wxBITMAP_TYPE_BMP);.
You will have similar issue with
{
wxBMPHandler h;
wxImage::AddHandler(&h);
} // End of life time of h
wxBitmap bm = wxBitmap(200, 200);
bm.SaveFile("file.bmp", wxBITMAP_TYPE_BMP);

seg fault after end of function (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.

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.

C++ MySQL++ Delete query statement brain killer question

I'm relatively new to the MySQL++ connector in C++, and have an really annoying issue with it already!
I've managed to get stored procedures working, however i'm having issues with the delete statements. I've looked high and low and have found no documentation with examples.
First I thought maybe the code needs to free the query/connection results after calling the stored procedure, but of course MySQL++ doesn't have a free_result method... or does it?
Anyways, here's what I've got:
#include <iostream>
#include <stdio.h>
#include <queue>
#include <deque>
#include <sys/stat.h>
#include <mysql++/mysql++.h>
#include <boost/thread/thread.hpp>
#include "RepositoryQueue.h"
using namespace boost;
using namespace mysqlpp;
class RepositoryChecker
{
private:
bool _isRunning;
Connection _con;
public:
RepositoryChecker()
{
try
{
this->_con = Connection(false);
this->_con.set_option(new MultiStatementsOption(true));
this->_con.set_option(new ReconnectOption(true));
this->_con.connect("**", "***", "***", "***");
this->ChangeRunningState(true);
}
catch(const Exception& e)
{
this->ChangeRunningState(false);
}
}
/**
* Thread method which runs and creates the repositories
*/
void CheckRepositoryQueues()
{
//while(this->IsRunning())
//{
std::queue<RepositoryQueue> queues = this->GetQueue();
if(queues.size() > 0)
{
while(!queues.empty())
{
RepositoryQueue &q = queues.front();
char cmd[256];
sprintf(cmd, "svnadmin create /home/svn/%s/%s/%s", q.GetPublicStatus().c_str(),
q.GetUsername().c_str(), q.GetRepositoryName().c_str());
if(this->DeleteQueuedRepository(q.GetQueueId()))
{
printf("query deleted?\n");
}
printf("Repository created!\n");
queues.pop();
}
}
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
//}
}
protected:
/**
* Gets the latest queue of repositories from the database
* and returns them inside a cool queue defined with the
* RepositoryQueue class.
*/
std::queue<RepositoryQueue> GetQueue()
{
std::queue<RepositoryQueue> queues;
Query query = this->_con.query("CALL sp_GetRepositoryQueue();");
StoreQueryResult result = query.store();
RepositoryQueue rQ;
if(result.num_rows() > 0)
{
for(unsigned int i = 0;i < result.num_rows(); ++i)
{
rQ = RepositoryQueue((unsigned int)result[i][0],
(unsigned int)result[i][1],
(String)result[i][2],
(String)result[i][3],
(String)result[i][4],
(bool)result[i][5]);
queues.push(rQ);
}
}
return queues;
}
/**
* Allows the thread to be shut off.
*/
void ChangeRunningState(bool isRunning)
{
this->_isRunning = isRunning;
}
/**
* Returns the running value of the active thread.
*/
bool IsRunning()
{
return this->_isRunning;
}
/**
* Deletes the repository from the mysql queue table. This is
* only called once it has been created.
*/
bool DeleteQueuedRepository(unsigned int id)
{
char cmd[256];
sprintf(cmd, "DELETE FROM RepositoryQueue WHERE Id = %d LIMIT 1;", id);
Query query = this->_con.query(cmd);
return (query.exec());
}
};
I've removed all the other methods as they're not needed...
Basically it's the DeleteQueuedRepository method which isn't working, the GetQueue works fine.
PS: This is on a Linux OS (Ubuntu server)
Many thanks,
Shaun
MySQL++ doesn't have a free_result method... or does it?
It doesn't need one. When the result object goes out of scope at the end of GetQueue(), all memory associated with it is automatically freed.
this->_con = Connection(false);
Three problems here:
When you create the RepositoryChecker object, you already have created a Connection object. If you need to pass different parameters to its constructor, you'd do that in the initialization list of the RepositoryChecker constructor, not in its body. Read your C++ book.
What you've done here instead is a) create a default Connection object, then b) create a different Connection object with exceptions turned off, then c) overwrite the first with the second. If that works, it's highly inefficient. MySQL++ Connection objects have had problems with their copy ctors in the past, so if you're using an old version of the library, it could explain your problems.
You're telling the Connection object (and every object it creates, even indirectly, which means pretty much everything in MySQL++) you don't want it to throw exceptions, but then you wrap it in a big try block. Pick one.
I'd suggest using exceptions — the default in MySQL++ — given the way your code is currently structured. If there is a query error way down in DeleteQueuedRepository(), there's no way to see what happened because you'd just pass false up to the caller, which is ignored because there is no else clause on the call. If you do this, log the e.what() message in your catch block. You're just throwing that information away right now.
There are several places where you're using constructs that look more like Python (or perhaps JavaScript) than C++. This makes me wonder if your problem isn't damage caused by some other misuse of C++.
On this line in particular, you're using the this pointer explicitly, for which there is no need in C++. This code does exactly the same thing:
_con = Connection(false);
Though again, the line should be replaced entirely, using the RepositoryChecker ctor initializer list instead.
Moving on...
sprintf(cmd, "DELETE FROM RepositoryQueue WHERE Id = %d LIMIT 1;", id);
As others have commented, you'd be better off using the Query stream interface:
Query q = _con.query();
q << "DELETE FROM RepositoryQueue WHERE Id = " << id << " LIMIT 1";
This has several advantages:
Fixes the type safety problem implied by the one who suggested changing your %d to %u. C++ IOStreams take care of that for you.
Automatic quoting of data inserted into the stream, if needed. (Which it isn't, in this case.)
Prevents any possibility of running off the end of the buffer. You could use the nonportable snprintf() instead here, but why?
If you're really happy with printf(), there's the template query interface instead.
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
Have you read the threads chapter in the user manual? You don't get thread safety for free in MySQL++. Your problem could be due to memory corruption.
Warren Young, MySQL++ Maintainer
Try changing "%d" to "%u" in sprintf.

Segfault when calling a method c++

I am fairly new to c++ and I am a bit stumped by this problem. I am trying to assign a variable from a call to a method in another class but it always segfaults. My code compiles with no warnings and I have checked that all variables are correct in gdb but the function call itself seems to cause a segfault. The code I am using is roughly like the following:
class History{
public:
bool test_history();
};
bool History::test_history(){
std::cout<<"test"; //this line never gets executed
//more code goes in here
return true;
}
class Game{
private:
bool some_function();
public:
History game_actions_history;
};
bool Game::some_function(){
return game_actions_history.test_history();
}
Any tips or advice is greatly appreciated!
EDIT: I edited the code so there is no more local_variable and the value returns directly. But it still segfaults. As for posting the actual code, it's fairly large, what parts should I post?
From what I can see there's nothing wrong with the code you've displayed. However, segfaults often are a good indication that you've got corrupted memory. It's happening some place else besides what you've shown and only happens to impact the code here. I'd look any place you're dealing with arrays, pointers, or any manual memory interactions.
I have used valgrind succesfully with a lot of segfaults.
and have you tried to run gdb with the coredump caused by the segfault? from man gdb:
gdb program core
To create a coredump you might have to set:
ulimit -c unlimited
Shot in the dark. (Game*)this is NULL ?
The code is fine but the example is too incomplete to say what's wrong. Some things I'd suggest:
Add printouts to each class's destructor and constructor:
Game::Game() { cerr << this << " Game::Game" << endl; }
Game::Game(Game const&) { cerr << this << " Game::Game(Game const&)" << endl; }
Game::~Game() { cerr << this << " Game::~Game" << endl; }
bool Game::some_function() { cerr << this << " Game::some_function()" << endl; ... }
This will reveal:
Null object pointers.
Bad/deleted class pointers.
Second, for debugging, I'd strongly recommended sending printouts to cerr instead of cout. cout is usually buffered (for efficiency) before being output, cerr is not (at least, this used to be the case). If your program quits without executing its error handlers, at_exit, etc..., you are more likely to see the output if it is unbuffered and printed immediately.
Thirdly, if your class declarations live in a header, the class definitions, live in one cpp file and the code that uses the class in yet another, you may get this kind of crash if either of the cpp files were not recompiled after you changed the header.
Some other possibilities are:
stack overflow: you've allocated a lot of memory on the stack because of deep recursion or are allocating objects containing large arrays of data as local variables (i.e. not created or the heap with new or malloc))
corrupted class vtable (usually only possible due to dependency errors in your build tools),
corrupted object vtable pointer: possible through misuse of pointers: using pointers to deleted memory, or incorrectly writing to an in-use address. Not likely in your example because there are no virtual functions.
maintaining a pointer or reference to an object allocated on the stack that has been deleted: the printout code above will uncover this case.
I am wondering because you have defined some_function() in private of the Game class. So the code structure which you have mentioned above will also throw error for that.