Segmentation fault for calling base class variable - c++

I have been using this code for a long time now in a project. However, I have recently added llvm-config --cxxflags --libs to the compiler in order to link with llvm libraries and it started generating seg faults. I have located the error and it happens when I call base class's variables.
Here is a small example of what I a doing
in Literals.hh
class LiteralObj : public RuleObj {
public:
LiteralObj();
LiteralObj(char *str);
~LiteralObj();
std::string raw_value;
static int literalobj_cnt;
int literalobj_id;
};
class LiteralIntObj : public LiteralObj{
public:
LiteralIntObj();
LiteralIntObj(char *str);
~LiteralIntObj();
void graphVis(std::ofstream &ofs, std::string &srcRef);
CODE_GENERATION;
int value;
};
Literals.cc
LiteralObj::LiteralObj() : RuleObj(){
ENTER_STATEMENT
raw_value = "";
literalobj_id = literalobj_cnt;
literalobj_cnt++;
}
LiteralObj::LiteralObj(char *str) : RuleObj(){
ENTER_STATEMENT
std::cerr << ruleobj_id << "\n";
raw_value = str;
literalobj_id = literalobj_cnt;
literalobj_cnt++;
}
LiteralObj::~LiteralObj()
{
ENTER_STATEMENT;
}
LiteralIntObj::LiteralIntObj() : LiteralObj()
{
ENTER_STATEMENT;
value = 0;
}
LiteralIntObj::LiteralIntObj(char *str) : LiteralObj(str)
{
ENTER_STATEMENT;
std::cerr << ruleobj_id << '\n';
value = stoi(raw_value);
}
LiteralIntObj::~LiteralIntObj()
{
ENTER_STATEMENT;
}
void LiteralIntObj::graphVis(std::ofstream &ofs, std::string &srcRef) {
ENTER_GRAPHVIS;
// -- define names
std::string currRef = "LiteralIntObj";
std::string name = "LiteralInt";
std::cerr << raw_value << "\n";
//it crashes here with SEGFAULT.
}
The code prints out raw_value of the base class fine for the first object, but, when the second is called SEGMENTATION Fault is generated.

When i changed compile options the pointers were set to 0xfffffff by default instead of 0. Therefore the check if (pointer) generated true even when the pointer were not initialized that led to calling function graphViz().

Related

Why does loading a block of memory from a DLL only crash at the second call to memmove?

This is the class in question (only functions that pertain to this question) and everything it depends on (all written myself). It provides an interface to a DLL.
struct MemRegion {
const uint64_t address;
const uint64_t size;
};
enum Version {
VERSION_US,
VERSION_JP
};
const struct MemRegion SEGMENTS[2][2] = {
{{1302528, 2836576},
{14045184, 4897408}},
{{1294336, 2406112},
{13594624, 4897632}},
};
using Slot = array<vector<uint8_t>, 2>;
class Game {
private:
Version m_version;
HMODULE m_dll;
const MemRegion* m_regions;
public:
Game(Version version, cstr dll_path) {
m_version = version;
m_dll = LoadLibraryA(dll_path);
if (m_dll == NULL) {
unsigned int lastError = GetLastError();
cerr << "Last error is " << lastError << endl;
exit(-2);
}
// this is a custom macro which calls a function in the dll
call_void_fn(m_dll, "sm64_init");
m_regions = SEGMENTS[version];
}
~Game() {
FreeLibrary(m_dll);
}
void advance() {
call_void_fn(m_dll, "sm64_update");
}
Slot alloc_slot() {
Slot buffers = {
vector<uint8_t>(m_regions[0].size),
vector<uint8_t>(m_regions[1].size)
};
return buffers;
}
void save_slot(Slot& slot) {
for (int i = 0; i < 2; i++) {
const MemRegion& region = m_regions[i];
vector<uint8_t>& buffer = slot[i];
cerr << "before memmove for savestate" << endl;
memmove(buffer.data(), reinterpret_cast<void* const>(m_dll + region.address), region.size);
cerr << "after memmove for savestate" << endl;
}
}
};
When I call save_slot(), it should copy two blocks of memory to a couple of vector<uint8_t>s. This does not seem to be the case, though. The function finishes the first copy, but throws a segmentation fault at the second memcpy. Why does it only happen at the second copy, and how can I get around this sort of issue?
Edit 1: This is what GDB gives me when the program terminates:
Thread 1 received signal SIGSEGV, Segmentation fault.
0x00007ffac2164452 in msvcrt!memmove () from C:\Windows\System32\msvcrt.dll
Edit 2: I tried accessing the segments individually. It works, but for some reason, I can't access both segments in the same program.
I found out that HMODULE is equivalent to void*. Since you can't really use pointer arithmetic on void*s, you have to cast it to a uint8_t* or equivalent to properly get an offset.
Here's what that looks like in practice:
void save_state(Slot& slot) {
uint8_t* const _dll = (uint8_t*)((void*)m_dll);
for (int i = 0; i < 2; i++) {
MemRegion segment = m_regions[i];
std::vector<uint8_t>& buffer = slot[i];
memmove(&buffer[0], _dll + segment.address, segment.size);
}
}

std string gets corrupted inside class

I am experimenting with building a simple nodegraph library for some projects i have in mind, but i'm hitting what i hope is a really simple roadblock very early on but it has me stumped.
I define objects called NodeDefinitions which are recipes from which nodes can be created in pre-defined configuraitons (number of ports/parameters etc.). NodeDefinition object contains PortDefinition objects that define each of the input/output ports. These PortDefinition objects contain their name (along with some other information in my full code, although removed below for brevity).
My Node class has a Node() constructor that creates a Node given a NodeDefition object. When I use this I create Port objects that each contain a pointer to their corresponding PortDefinition. When I try and print out the name of the port (derived from/stored in the PortDefinition object) it gets corrupted.
Through a little trial and error i have managed to find that if i just pass a std::vector directly to an alternate Node() constructor, then everything appears to work fine.
In the example code below i'm printing out the port names (only one port here), both inside the constructor and then after in the caller.
The definition classes.
class PortDefinition
{
public:
PortDefinition(const std::string & name) : m_name(name)
{}
std::string m_name;
};
class NodeDefinition
{
public:
NodeDefinition(std::vector<PortDefinition> portDefinitions) :
m_portDefinitions(portDefinitions)
{}
std::vector<PortDefinition> m_portDefinitions;
};
The concrete object classes.
class Port
{
public:
Port(PortDefinition * portDefinition) :
m_portDefinition(portDefinition)
{}
const PortDefinition * m_portDefinition;
};
class Node
{
public:
Node(NodeDefinition nodeDefinition) {
std::vector<PortDefinition> portDefs = nodeDefinition.m_portDefinitions;
for (auto & it : portDefs) {
Port newPort = Port( &it );
m_ports.push_back( newPort );
}
print();
}
Node(std::vector<PortDefinition> portDefs) {
for (auto & it : portDefs) {
Port newPort = Port( &it );
m_ports.push_back( newPort );
}
print();
}
void print() const {
std::cout << m_ports.size() << " : ";
for (auto it : m_ports) {
std::cout << "'" << it.m_portDefinition->m_name << "'" << std::endl;
}
}
private:
std::vector<Port> m_ports;
};
The test code.
int main (int argc, const char *argv[])
{
std::vector<PortDefinition> portDefinitions;
portDefinitions.push_back( PortDefinition("Port_A") );
NodeDefinition nodeDefinition = NodeDefinition(portDefinitions);
std::cout << "constuctor N1 : ";
Node N1 = Node(nodeDefinition);
std::cout << "main func N1 : ";
N1.print();
std::cout << std::endl;
std::cout << "constuctor N2 : ";
Node N2 = Node(portDefinitions);
std::cout << "main func N2 : ";
N2.print();
return 1;
}
All of the code can be compiled in a single file together.
When I run this get the following output.
constuctor N1 : 1 : 'Port_A'
main func N1 : 1 : ''
constuctor N2 : 1 : 'Port_A'
main func N2 : 1 : 'Port_A'
As you can see when i print out the port name after using the Node() constructor that uses the NodeDefinition object the name is empty, sometimes I get garbage there instead, which makes me think something is corrupting memory somehow, but i'm a bit lost as to why.
std::vector<PortDefinition> portDefs = nodeDefinition.m_portDefinitions;
for (auto & it : portDefs) {
Port newPort = Port( &it );
m_ports.push_back( newPort );
}
This code is the problem. portDefs is a copy of nodeDefinition.m_portDefinitions, being destroyed when the constructor is finished. But you store a pointer to the these objects with Port(&it).
The print() in the constructor should work fine, but the print() in main now accesses the destroyed copies, which is undefined behaviour.
A possible solution would be to store shared_ptr of your PortDefinition or just store a copy in Port.

Accessor Method to view private variable based on argument in a class in c++?

My problem is that I have many variables in my class and I want them to be accessed via an accessor method. Of course I could have several accessor functions to output my private variables but how can I make it so I can access any of them via an argument. My class:
class Character {
public:
void setAttr(string Sname,int Shealth,int SattackLevel,int SdefenseLevel) {
name = Sname;
health = Shealth;
attackLevel = SattackLevel;
defenseLevel = SdefenseLevel;
}
int outputInt(string whatToOutput) {
return whatToOutput //I want this to either be health, attackLevel or defenseLevel
}
private:
string name;
int health;
int attackLevel;
int defenseLevel;
};
Basically what I want to know is how do I return a private variable in regards to the outputInt function. Most OOP tutorials have one function to return each variable which seems like a very unhealthy thing to do in a large program.
C++ doesn't support what you try to accomplish: reflection or detailed runtime information about objects. There is something called "Run-Time Type Information" in C++, but it can't provide information about your variable name: the reason is because, in the compiled and linked binary this information (names of your variables) will not be necessarily present anymore.
However, you can accomplish something close to that, using i.e. std::unordered_map instead of plain integer variables. So it's possible to access values by their names, as strings.
Please consider the following code:
#include <string>
#include <iostream>
#include <unordered_map>
using namespace std;
class Character {
public:
void setAttr(const string& Sname, int Shealth, int SattackLevel, int SdefenseLevel) {
name = Sname;
values.insert(std::make_pair("health", Shealth));
values.insert(std::make_pair("attackLevel", SattackLevel));
values.insert(std::make_pair("defenseLevel", SdefenseLevel));
}
int outputInt(const string& whatToOutput) {
return values.at(whatToOutput);
}
private:
string name;
std::unordered_map<std::string, int> values;
};
int main(int argc, char* argv[]) {
Character yourCharacter;
yourCharacter.setAttr("yourName", 10, 100, 1000);
std::cout << "Health: " << yourCharacter.outputInt("health") <<std::endl;
std::cout << "Attack level: " << yourCharacter.outputInt("attackLevel") << std::endl;
std::cout << "Defense level: " << yourCharacter.outputInt("defenseLevel") << std::endl;
return 0;
}
It will output as expected:
Health: 10
Attack level: 100
Defense level: 1000
Another option without dependency on unordered_map would be, to use predefined static strings for your variable names and an array or vector for your values. So we could replace the class Character above with something like:
static std::string variableNames[3] = {
"health",
"attackLevel",
"defenseLevel"
};
class Character {
public:
void setAttr(const string& Sname, int Shealth, int SattackLevel, int SdefenseLevel) {
name = Sname;
variableValues[0] = Shealth;
variableValues[1] = SattackLevel;
variableValues[2] = SdefenseLevel;
}
int outputInt(const string& whatToOutput) {
int retVal = 0;
for (size_t i = 0; i < sizeof(variableNames)/sizeof(std::string); ++i) {
if (!whatToOutput.compare(variableNames[i])) {
retVal = variableValues[i];
}
}
return retVal;
}
private:
string name;
int variableValues[3];
};
And getting still same output. However, here you have to manage a list with all your variable names inside the string array manually - I don't like this solution and would prefer one of the others above personally.
Most common ways in C++ to handle such a design is to have seperate getHealth(), getAttackLevel(), getDefenseLevel() functions instead. However, this will miss one use-case, which is: if you want to let the user input a string, like i.e. "health" and display the corresponding variable then, you would need to write code by yourself to call the corresponding getXXX() function. If this is not a issue in your case, consider the following code which is much cleaner:
#include <string>
#include <iostream>
using namespace std;
class Character {
public:
void setAttr(const string& Sname, int Shealth, int SattackLevel, int SdefenseLevel) {
name = Sname;
health = Shealth;
attackLevel = SattackLevel;
defenseLevel = SdefenseLevel;
}
int getHealth() const { return health; }
int getAttackLevel() const { return attackLevel; }
int getDefenseLevel() const { return defenseLevel; }
private:
string name;
int health, attackLevel, defenseLevel;
};
int main(int argc, char* argv[]) {
Character yourCharacter;
yourCharacter.setAttr("yourName", 10, 100, 1000);
std::cout << "Health: " << yourCharacter.getHealth() <<std::endl;
std::cout << "Attack level: " << yourCharacter.getAttackLevel() << std::endl;
std::cout << "Defense level: " << yourCharacter.getDefenseLevel() << std::endl;
return 0;
}
One other unrelated advice: Instead of using string as parameter types for your functions, use const string& (const reference to string; see my example code above). This allows easier calling of your functions (they can be called directly with an string literal without the need to create additional variables in the calling code) and they will not make a additional unnecessary copy. The only copy then will take place at: name = Sname; (in your code two copies took place).
I don't know if it can be a good idea for you, but you can use a public typedef struct that you pass by reference and set your value.
class Character {
public:
//...
typedef struct allvalues{
string vname;
int vhealth;
int vattackLevel;
int vdefenseLevel;
}allvalues;
void getValues(allvalues& val){
val.vname = name;
val.vhealth = health;
val.vattackLevel = attackLevel;
val.vdefenseLevel = detenseLevel;
}
//...
};
//...
//somewhere in the code
Character myCarac;
//...
//Here how to use it
Character::allvalues values;
myCarac.getValues(values);

Shared library and member functions

I'm facing a little problem in C++.
So, I have a game, a sort of Snake, and I want to do it with three different graphic libraries. (like libsdl.so, libndk.so and libQt.so).
I have the following classes :
DisplaySDL.hh :
#ifndef DISPLAYSDL_HH__
# define DISPLAYSDL_HH__
#include "IDisplay.hh"
class DisplaySdl : public IDisplay
{
public:
DisplaySdl();
~DisplaySdl();
void Boucle(Core &core);
};
#endif
DisplaySDL.cpp:
#include <iostream>
#include "DisplaySdl.hh"
extern "C"
{
IDisplay* createDisplay()
{
return new DisplaySdl();
}
}
DisplaySdl::DisplaySdl()
{
std::cout << "SDL Loaded" << std::endl;
}
DisplaySdl::~DisplaySdl()
{
}
void DisplaySdl::Boucle(Core &core)
{
std::cout << "this is just a test" << std::endl;
}
And I have my Interface "IDisplay" :
#ifndef IDISPLAY_HH__
# define IDISPLAY_HH__
#include "../Core/Core.hh"
class IDisplay
{
public:
virtual ~IDisplay() {}
// virtual void dispSnake(Snake snake) = 0;
// virtual void dispBlock(Block block) = 0;
// virtual void dispMap(Map map) = 0;
virtual void Boucle(Core &core);
};
#endif
(I just put the DisplaySDL.hh and DisplaySDL.cpp as the other libs have the same design pattern / functions)
And here's the code that load the different libraries and create a IDisplay * object. :
IDisplay* LibGestionnary::loadLibFromName(const std::string &libname)
{
IDisplay* (*external_creator)();
void* dlhandle;
dlhandle = dlopen(libname.c_str(), RTLD_LAZY);
if (dlhandle == NULL)
std::cout << dlerror() << std::endl;
external_creator = reinterpret_cast<IDisplay* (*)()>(dlsym(dlhandle, "createDisplay"));
if (external_creator == NULL)
std::cout << dlerror() << std::endl;
IDisplay* Display = external_creator();
dlclose(dlhandle);
return (Display);
}
The thing is that my function loadLibFromName() is working great, it loads the library that I tell it, BUT only when I don't have any function member in any of my graphic lib.
If I remove the "boucle()" function from my code, it works great as shown below :
./nibbler 20 20 ./libsdl.so
SDL Loaded
Otherwise, that's what I get when I try to load the lib :
yanis#b3nd3r:~/Projets/C++/nibbler$ ./nibbler 20 20 ./libsdl.so
./libsdl.so: undefined symbol: _ZTI8IDisplay
./nibbler: undefined symbol: createDisplay
Segmentation Fault
Any help ? :)
Well, I managed to get it working... the "=0;" was missing in my interface for the "Boucle()" function.
But I'm facing another problem... I can call my boucle() function, but whenever I do it, I get a segfault...
Here's the code I use :
int main(int argc, char **argv)
{
IDisplay *display;
display = gestionnary.loadLibFromName(std::string(argv[3]));
display->Boucle();
}
And GDB tells me that :
Program received signal SIGSEGV, Segmentation fault.
0x000000000040b325 in main (argc=4, argv=0x7fffffffe538, env=0x7fffffffe560) at Core/main.cpp:44
44 display->Boucle();
The Boucle() function consists in only on print of a phrase...

Segmentation Fault when trying to push a string to the back of a list

I am trying to write a logger class for my C++ calculator, but I'm experiencing a problem while trying to push a string into a list.
I have tried researching this issue and have found some information on this, but nothing that seems to help with my problem. I am using a rather basic C++ compiler, with little debugging utilities and I've not used C++ in quite some time (even then it was only a small amount).
My code:
#ifndef _LOGGER_H_
#define _LOGGER_H_
#include <iostream>
#include <list>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::list;
using std::string;
class Logger
{
private:
list<string> mEntries;
public:
Logger() {}
~Logger() {}
// Public Methods
void WriteEntry(const string& entry)
{
mEntries.push_back(entry);
}
void DisplayEntries()
{
cout << endl << "**********************" << endl
<< "* Logger Entries *" << endl
<< "**********************" << endl
<< endl;
for(list<string>::iterator it = mEntries.begin();
it != mEntries.end(); it++)
{
// *** BELOW LINE IS MARKED WITH THE ERROR ***
cout << *it << endl;
}
}
};
#endif
I am calling the WriteEntry method by simply passing in a string, like so:
mLogger->WriteEntry("Testing");
Any advice on this would be greatly appreciated.
* CODE ABOVE HAS BEEN ALTERED TO HOW IT IS NOW *
Now, the line:
cout << *it << endl;
causes the same error. I'm assuming this has something to do with how I am trying to get the string value from the iterator.
The code I am using to call it is in my main.cpp file:
#include <iostream>
#include <string>
#include <sstream>
#include "CommandParser.h"
#include "CommandManager.h"
#include "Exceptions.h"
#include "Logger.h"
using std::string;
using std::stringstream;
using std::cout;
using std::cin;
using std::endl;
#define MSG_QUIT 2384321
#define SHOW_LOGGER true
void RegisterCommands(void);
void UnregisterCommands(void);
int ApplicationLoop(void);
void CheckForLoggingOutput(void);
void ShowDebugLog(void);
// Operations
double Operation_Add(double* params);
double Operation_Subtract(double* params);
double Operation_Multiply(double* params);
double Operation_Divide(double* params);
// Variable
CommandManager *mCommandManager;
CommandParser *mCommandParser;
Logger *mLogger;
int main(int argc, const char **argv)
{
mLogger->WriteEntry("Registering commands...\0");
// Make sure we register all commands first
RegisterCommands();
mLogger->WriteEntry("Command registration complete.\0");
// Check the input to see if we're using the program standalone,
// or not
if(argc == 0)
{
mLogger->WriteEntry("Starting application message pump...\0");
// Full version
int result;
do
{
result = ApplicationLoop();
} while(result != MSG_QUIT);
}
else
{
mLogger->WriteEntry("Starting standalone application...\0");
// Standalone - single use
// Join the args into a string
stringstream joinedStrings(argv[0]);
for(int i = 1; i < argc; i++)
{
joinedStrings << argv[i];
}
mLogger->WriteEntry("Parsing argument '" + joinedStrings.str() + "'...\0");
// Parse the string
mCommandParser->Parse(joinedStrings.str());
// Get the command names from the parser
list<string> commandNames = mCommandParser->GetCommandNames();
// Check that all of the commands have been registered
for(list<string>::iterator it = commandNames.begin();
it != commandNames.end(); it++)
{
mLogger->WriteEntry("Checking command '" + *it + "' is registered...\0");
if(!mCommandManager->IsCommandRegistered(*it))
{
// TODO: Throw exception
mLogger->WriteEntry("Command '" + *it + "' has not been registered.\0");
}
}
// Get each command from the parser and use it's values
// to invoke the relevant command from the manager
double results[commandNames.size()];
int currentResultIndex = 0;
for(list<string>::iterator name_iterator = commandNames.begin();
name_iterator != commandNames.end(); name_iterator++)
{
string paramString = mCommandParser->GetCommandValue(*name_iterator);
list<string> paramStringArray = StringHelper::Split(paramString, ' ');
double params[paramStringArray.size()];
int index = 0;
for(list<string>::iterator param_iterator = paramStringArray.begin();
param_iterator != paramStringArray.end(); param_iterator++)
{
// Parse the current string to a double value
params[index++] = atof(param_iterator->c_str());
}
mLogger->WriteEntry("Invoking command '" + *name_iterator + "'...\0");
results[currentResultIndex++] =
mCommandManager->InvokeCommand(*name_iterator, params);
}
// Output all results
for(int i = 0; i < commandNames.size(); i++)
{
cout << "Result[" << i << "]: " << results[i] << endl;
}
}
mLogger->WriteEntry("Unregistering commands...\0");
// Make sure we clear up our resources
UnregisterCommands();
mLogger->WriteEntry("Command unregistration complete.\0");
if(SHOW_LOGGER)
{
CheckForLoggingOutput();
}
system("PAUSE");
return 0;
}
void RegisterCommands()
{
mCommandManager = new CommandManager();
mCommandParser = new CommandParser();
mLogger = new Logger();
// Known commands
mCommandManager->RegisterCommand("add", &Operation_Add);
mCommandManager->RegisterCommand("sub", &Operation_Subtract);
mCommandManager->RegisterCommand("mul", &Operation_Multiply);
mCommandManager->RegisterCommand("div", &Operation_Divide);
}
void UnregisterCommands()
{
// Unregister each command
mCommandManager->UnregisterCommand("add");
mCommandManager->UnregisterCommand("sub");
mCommandManager->UnregisterCommand("mul");
mCommandManager->UnregisterCommand("div");
// Delete the logger pointer
delete mLogger;
// Delete the command manager pointer
delete mCommandManager;
// Delete the command parser pointer
delete mCommandParser;
}
int ApplicationLoop()
{
return MSG_QUIT;
}
void CheckForLoggingOutput()
{
char answer = 'n';
cout << endl << "Do you wish to view the debug log? [y/n]: ";
cin >> answer;
switch(answer)
{
case 'y':
ShowDebugLog();
break;
}
}
void ShowDebugLog()
{
mLogger->DisplayEntries();
}
// Operation Definitions
double Operation_Add(double* values)
{
double accumulator = 0.0;
// Iterate over all values and accumulate them
for(int i = 0; i < (sizeof values) - 1; i++)
{
accumulator += values[i];
}
// Return the result of the calculation
return accumulator;
}
double Operation_Subtract(double* values)
{
double accumulator = 0.0;
// Iterate over all values and negativel accumulate them
for(int i = 0; i < (sizeof values) - 1; i++)
{
accumulator -= values[i];
}
// Return the result of the calculation
return accumulator;
}
double Operation_Multiply(double* values)
{
double accumulator = 0.0;
for(int i = 0; i < (sizeof values) - 1; i++)
{
accumulator *= values[i];
}
// Return the value of the calculation
return accumulator;
}
double Operation_Divide(double* values)
{
double accumulator = 0.0;
for(int i = 0; i < (sizeof values) - 1; i++)
{
accumulator /= values[i];
}
// Return the result of the calculation
return accumulator;
}
Did you remember to call mLogger = new Logger at some point? Did you accidantally delete mLogger before writing to it?
Try running your program in valgrind to see whether it finds any memory errors.
After your edit, the solution seem clear:
Your first line in main() is :
mLogger->WriteEntry("Registering commands...\0");
Here mLogger is a pointer that has never been initialized. This is "undefined behaviour", meaning anything can appen, often bad things.
To fix this you can either make it a "normal" variable, not a pointer or create a Logger instance using new (either at the declaration or as the first line in main).
I suggest you to not use a pointer to be sure the logger is always there and is automatically destroyed.
By the way, it seems like you want to create every instance of objects on the heap using pointers. It's not recommanded if it's not necessary. You should use pointers ONLY if you want to explicitely state the creation (using new) and destruction (using delete) of the instance object. If you just need it in a specific scope, don't use a pointer. You might come from another language like Java or C# where all objects are referenced. If so, you should start learning C++ like a different language to avoid such kind of problem. You should learn about RAII and other C++ scpecific paradigm that you cannot learn in those languages. If you come from C you should too take it as a different language. That might help you avoid complex problems like the one you showed here. May I suggest you read some C++ pointer, references and RAII related questions on stackoverflow.
First, you don't need to create the std::list on the heap. You should just use it as a normal member of the class.
class Logger
{
private:
list<string> mEntries; // no need to use a pointer
public:
Logger() // initialization is automatic, no need to do anything
{
}
~Logger() // clearing and destruction is automatic too, no need to do anything
{
}
//...
};
Next, entryData don't exist in this code so I guess you wanted to use entry. If it's not a typo then you're not providing the definition of entryData that is certainly the source of your problem.
In fact I would have written your class that way instead:
class Logger
{
private:
list<string> mEntries;
public:
// no need for constructor and destructor, use the default ones
// Public Methods
void WriteEntry(const string& entry) // use a const reference to avoid unnecessary copy (even with optimization like NRVO)
{
mEntries.push_back( entry ); // here the list will create a node with a string inside, so this is exactly like calling the copy constructor
}
void DisplayEntries()
{
cout << endl << "**********************" << endl
<< "* Logger Entries *" << endl
<< "**********************" << endl
<< endl;
for(list<string>::iterator it = mEntries.begin();
it != mEntries.end(); ++it) // if you want to avoid unnecessary copies, use ++it instead of it++
{
cout << *it << endl;
}
}
};
What's certain is that your segfault is from usage outside of this class.
Is an instance of Logger being copied anywhere (either through a copy constructor or operator=)? Since you have mEntries as a pointer to a list, if you copy an instance of Logger, they will share the value of the pointer, and when one is destructed, it deletes the list. The original then has a dangling pointer. A quick check is to make the copy constructor and operator= private and not implemented:
private:
void operator=(const Logger &); // not implemented
Logger(const Logger &); // not implemented
When you recompile, the compiler will flag any copies of any Logger instances.
If you need to copy instances of Logger, the fix is to follow the Rule of 3:
http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29
You can do this by eliminating the need for the destructor (by not using a pointer: list<string> mEntries), or by adding the needed code to the copy constructor and operator= to make a deep copy of the list.
You only need to do
list<string> entries;
entries.push_back();
You do not need to create a pointer to entries.
Nothing too obvious, though you typed
mEntries->push_back(string(entryData));
and I htink you meant entry instead of entryData. You also don't need the string conversion on that line, and your function should take entry by const reference.
However, none of these things would cause your program to segfault. What compiler are you using?
You're missing the copy constructor. If the Logger object is copied and the original deleted, you'll be dereferencing memory that was previously deleted.
A simplified example of the problem
Logger a;
{
Logger b;
a=b;
}
a.WriteEntry("Testing");
Add a copy constructor.
Logger(const Logger& item)
{
mEntries = new list<string>();
std::copy(item.mEntries->begin(), item.mEntries->end(), std::back_inserter(*mEntries));
}