Method can not initialize value c++ - c++

Firstly I initialize value in constructor in Ford Bellman claas
FordBellman::FordBellman() {
this->vertexCount=0;
this->vertexFirst=0;
this->edgeCount=0;
this->wage=0;
this->matrix=0;
this->distance=0;
this->predecessor=0;
}
next I have reference in argument of initialize method in FordBellman
void FordBellman::initialize(const AdjacencyMatrix &am)
{
this->vertexCount=am.getVertexCount();
this->vertexFirst=am.getVertexFirst();
this->edgeCount=am.getEdgeCount();
this->wage=am.getWage();
this->matrix=am.getMatrix();
cout << vertexCount;
cout << vertexFirst;
.....
}
in main class I do it in this way
int main() {
AdjacencyMatrix am;
FordBellman fb;
am.createFromFile("matrix.txt");
fb.initialize(am);
}
And if i call fb.initialize(am) console show nothing(should show cout )
Can you tell me what I do wrong ?
repo https://github.com/likoms/Graph/

When I tried to run code from github repository about you sad I got segmentation fault. The reason was in the file FordBellman.cpp line 42. There you didn't allocate array but you used it.
The reason why you didn't see anything is in the fact your program is terminated before it prints something. To be accurate it's happening inside of am.createFromFile("matrix.txt");
Try to write memory allocation for predecessor and I think your code will start working.
I'm a bit confused that you doesn't get message about segmentation fault. What development environment you use?

Related

Errors with initialization of an unordered_map inside of a class

The error I'm getting is Exception thrown at 0x00007FF77339C476 in VirusSimulator.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
I've gone through my code with Visual Studio's debugger, and it seems like the error is from an attempt to call .size() on a unordered map of class objects.
Specifically, in the implementation of "list":
size_type size() const _NOEXCEPT
{ // return length of sequence
return (this->_Mysize());
}
When stepping through with the debugger and keeping an eye on local variables, I see: this 0xccccccccccccce0c folders={ size=??? }
(folders being the map of class variables)
Just below is a section of int main() where I manually initialize a default folder in each computer's drive's map of folders:
vector<Computer> macs;
for (int i = 0; i < mac_amount; i++)
{
macs.push_back(Computer(OSX)); //Initialize a computer with an operating system
}
for (int i = 0; i < macs.size(); i++)
{
//... Here is some code initializing connections between the computer objects
//and here is the manual insert of folders into the map
macs[i].getDrive()->addFolder("default"); //This used to be in the computers constructor but I moved it out here for testing
}
definition of addFolder:
void Harddrive::addFolder(string name)
{
Folder new_folder;
new_folder.set_name(name);
folders.insert(std::pair<string, Folder>(name, new_folder));
}
Basically, a random computer object then runs a virus that attempts to install itself to every other connected computer object by accessing the list of connections that is has, which contain pointers to the other computer objects.
It then de-references these and attempts to find the default folder on each respective computer's harddrive, but then fails to do so, claiming that the folder is uninitialized?
If any other pieces of my code are needed, then the full code can be found at https://github.com/BananaSky/VirusSimulator/tree/UnstableNetworkAdditions
Most of the code I've already tested for bugs, and that's why I've only posted such a small portion.
Any help is much appreciated!! (But also, it's getting late here and I might be going to sleep soon, so I apologize if I can't respond right away)
--ALSO: Please note that this is just a simulation and that I'm not actually intending to create any form of computer virus.
Here is the section of code where the error occurs (inside Virus.cpp):
vector<int> vulnerableConnectionIPs = installedOn->getNetworkAdapter()->getConnection()->getConnections();
for (int i = 0; i < vulnerableConnectionIPs.size(); i++)
{
Computer* accessRequest = installedOn->getNetworkAdapter()->getConnection()->getConnect(vulnerableConnectionIPs[i])->giveAccess();
if (accessRequest != NULL && accessRequest != installedOn)
{
if (accessRequest->getDrive()->getFolders()) //Error occurs here
{
accessRequest->Install(this, "default"); //Infect if infectable :)
}
else
{
cout << "No folders exist on " << accessRequest->getDrive()->getModel() << endl;
}
}
}
I'm working on replicating this on a smaller scale, and I'll probably get that posted by tomorrow
A memory address of 0xcccccccccccccccc (64-bit) or 0xcccccccc (32-bit) is Visual Studio's way of denoting an uninitialized block of memory. There's also 0xfeeefeee for already free'd and 0x00000000 for a null pointer.
Check that you have actually stored a value in the variable you are trying to access.
The values actually shown from error dialogs may be offset to values close to the above locations, you'll just have to trace through the program.
Your initial description of the error also points to at least trying to de-reference a null pointer.
More code would be helpful.

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.

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.

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.

Class Problem (c++ and prolog)

I am using the C++ interface to Prolog (the classes and methods of SWI-cpp.h). For working out a simple backtracking that john likes mary and emma and sara:
likes(john, mary).
likes(john, emma).
likes(john, ashley).
I can just do:
{
PlFrame fr;
PlTermv av(2);
av[0] = PlCompound("john");
PlQuery q("likes", av);
while (q.next_solution())
{
cout << (char*)av[1] << endl;
}
}
This works in a separate code, so the syntax is correct. But I am also trying to get this
simple backtracking to work within a class:
class UserTaskProlog
{
public:
UserTaskProlog(ArRobot* r);
~UserTaskProlog();
protected:
int cycles;
char* argv[1];
ArRobot* robot;
void logTask();
};
This class works fine, with my cycles variable incrementing every robot cycle. However, when I run my main code, I get an Unhandled Exception error message:
UserTaskProlog::UserTaskProlog(ArRobot* r) : robotTaskFunc(this, &UserTaskProlog::logTask)
{
cycles = 0;
PlEngine e(argv[0]);
PlCall("consult('myFile.pl')");
robot->addSensorInterpTask("UserTaskProlog", 50, &robotTaskFunc);
}
UserTaskProlog::~UserTaskProlog()
{
robot->remSensorInterpTask(&robotTaskFunc);
// Do I need a destructor here for pl?
}
void UserTaskProlog::logTask()
{
cycles++;
cout << cycles;
{
PlFrame fr;
PlTermv av(2);
av[0] = PlCompound("john");
PlQuery q("likes", av);
while (q.next_solution())
{
cout << (char*)av[1] << endl;
}
}
}
I have my opening and closing brackets for PlFrame. I have my frame, my query, etc... The exact same code that backtracks and prints out mary and emma and sara. What am I missing here that I get an error message?
Here is what I think the code should do: I expect mary and emma and sara to be printed out once, every time cycles increments. However, it opens SWI-cpp.h file automatically and points to class PlFrame. What is it trying to tell me? I don't see anything wrong with my PlFrame class declaration.
Thanks,
You cannot pass pointers to instance methods like this, you probably have to create C function wrapper for passing to addSensorInterpTask(). This seems to be the root of your problem, as robot calls the method with incorrect parameters. Also, you should catch PlException and check what it tells you.
Anyway, your example cannot be compiled as it is, since it is incomplete (what is ArRobot?) and imprecise (ashley v.s. sara). Please try to imagine how other people could reproduce your problem without much a of a hassle before submitting a question.