Getting Segmentation Error in code - c++

Trying to create a function which will fill a vector of objects with initialized objects.
Please help.
ERROR: Segmentation fault (core dumped)
EDIT:
Ok so, problem seems to be occurring in the line when trying to access OBJ[0].age.
Also forgot the Point2d function comes from OpenCV libraries which I forgor to add, but they dont seem to contribute to the error in any way.
#include <iostream>
#include <vector>
struct objtracker
{
int age;
vector<int> frID;
vector<Point2d> cent;
objtracker()
{
age = 1;
}
~objtracker()
{
// Destroy ObjectTracker
}
};
vector<objtracker> OBJ;
void create_new_tracker(vector<objtracker> OBJ,Point2d cent,int frameID,objtracker O){
O.cent.push_back(cent);
O.frID.push_back(frameID);
}
int main(){
Mat Y;
Y = imread("hor.jpeg",CV_LOAD_IMAGE_COLOR);
Point2d J;
J.x = 100;
J.y = 100;
int frameID = 100;
objtracker O;
create_new_tracker(OBJ,J,frameID,O);
create_new_tracker(OBJ,J,frameID,O);
create_new_tracker(OBJ,J,frameID,O);
create_new_tracker(OBJ,J,frameID,O);
create_new_tracker(OBJ,J,frameID,O);
cout<<OBJ[0].age<<"\n";
return 1; }

void create_new_tracker(vector<objtracker> OBJ,Point2d cent,int frameID,objtracker O){
O.cent.push_back(cent);
O.frID.push_back(frameID);
}
You never add any objtracker's to OBJ inside this function.
And even if you did, it won't be reflected as it is passed by value
You might want something like
void create_new_tracker(vector<objtracker> &OBJ,Point2d cent,int frameID,objtracker O)
{
O.cent.push_back(cent);
O.frID.push_back(frameID);
OBJ.push_back(O);
}

Related

Understand pointers

#include <iostream>
using namespace std;
class idk{
public:
int x;
int y;
};
void obj(idk* obj[]){
obj[0]-> x = 1000;
obj[0]-> y = 30;
}
int main(){
idk *z[5];
obj(z);
cout << z[0]->x;
return 0;
}
I am just trying out how to use pointers. The problem is when I set my array 'z' size to 5 or any number it doesn't do anything, however when I make it 10 it then prints out the correct output. Ive tried pasting the code into an online compiler and it also plays up there but with other numbers. Is my code wrong or missing some things?
In this
idk *z[5];
you declare 5 idk pointers. These are only pointers that you can assign to point at idks, but you have not created any actual idks. When you later dereference the first pointer you get undefined behavior since it's not actually pointing at an idk:
void obj(idk* obj[]){
obj[0]-> x = 1000; // BOOM
Making the array of pointers actually point at idk instances can be made in many different ways. Here's one:
#include <iostream>
class idk{
public:
int x;
int y;
};
void obj(idk* obj[]){
obj[0]-> x = 1000;
obj[0]-> y = 30;
}
int main(){
idk instances[5];
idk *z[5]{
&instances[0],
&instances[1],
&instances[2],
&instances[3],
&instances[4],
}; // now all five point at one idk instance each
obj(z);
std::cout << z[0]->x;
}
Another option would be to skip the pointer array completely:
#include <iostream>
class idk {
public:
int x;
int y;
};
void obj(idk obj[]) {
obj[0].x = 1000;
obj[0].y = 30;
}
int main() {
idk z[5];
obj(z);
std::cout << z[0].x;
}

How to return a pointer to a ragged array through a function argument?

I need to modifiy an existing API and basically the only option I have is returning a pointer to a ragged array through a function argument (this would normally not be me personal preference). I can't get my head around doing this and keep getting a segmentation fault at this part of the code:
void getMxByArg(int ***pppX) {
*pppX = m_ppMx; // SEGMENTATION FAULT HERE
}
I've provided an example below which doesn't have any external dependencies and encapsulates the problem.
#include <stdint.h>
#include <iostream>
using namespace std;
class Mx {
public:
Mx() {
int *buff01 = (int*)malloc(3 * sizeof(int));
int *buff02 = (int*)malloc(3 * sizeof(int));
buff01[0] = 0;
buff01[1] = 1;
buff01[2] = 3;
buff02[0] = 4;
buff02[1] = 5;
buff02[2] = 6;
m_n = 2;
m_ppMx = (int**)malloc(m_n * sizeof(int*));
m_ppMx[0] = buff01;
m_ppMx[1] = buff02;
}
~Mx() {
for (int i=0; i<m_n; ++i) {
free(m_ppMx[i]);
}
free(m_ppMx);
}
int** getMx() {
return m_ppMx;
}
void getMxByArg(int ***pppX) {
*pppX = m_ppMx; // SEGMENTATION FAULT HERE
}
private:
int **m_ppMx;
int m_n;
};
int main()
{
Mx mx;
// SUCCESS
int **ppX = mx.getMx();
// FAILURE, Results in segmentation fault in getMxByArg
int ***pppX;
mx.getMxByArg(pppX);
return 0;
}
In the posted code, you are dereferencing an uninitialized pointer. That's cause for undefined behavior.
The solution is:
Create a variable of type int**.
Pass the address of that variable to the function.
int **ppX2;
mx.getMxByArg(&ppX2);
Another option is to change the argument type to int**&.
void getMxByArg(int**& ppX) {
ppX = m_ppMx;
}
Then, you can use:
int **ppX2;
mx.getMxByArg(ppX2);

Unhandled exception at 0x000FBA44 in Top Down Shooter

I recently posted a question dealing with linker errors... Well for whatever reason those errors went away and is replaced with this. When I try to run my program, the window opens and it appears to run, however Visual Studio 2013 then presents me with the error:
Unhandled exception at 0x000FBA44 in Top Down Shooter.exe: 0xC0000005: Access violation reading location 0xCCCCCCD0.
And then takes me to a xutility file with a breakpoint here:
#if _ITERATOR_DEBUG_LEVEL == 2
if (_Myproxy != _Parent_proxy)
{ // change parentage
_Lockit _Lock(_LOCK_DEBUG);
_Orphan_me();
_Mynextiter = _Parent_proxy->_Myfirstiter;
_Parent_proxy->_Myfirstiter = this;
_Myproxy = _Parent_proxy;
}
The arrow is on the _Mynextiter line. Does anyone know what is happening? I was initially using iterators to help go through some lists that I had, but I commented them out yet I still get this error and I'm not sure why
Edit:
Ok, So after going back through the stack of methods called, the last piece of code that was called that was mine was this:
ChunkManager::ChunkManager(b2World *w){
AbstractChunk *chunk = generateChunk(0, 0);
loadedChunks.push_back(*chunk);
for (int i = 0; i < 64; i++){
for (int p = 0; p < 64; p++){
if (std::rand() > .7){
AbstractBlock block(i, p, 0, w);
}
}
}
}
Now I remember when I wrote this I thought it was strange because loadedChunks is an std::list... I have never used lists so I thought it was strange that the list would only accept a pointer to a pointer to an object where in the <> of the list it clearly takes an object... I think this might be the source of my problem but I don't know how to fix it
Second Edit: Here is the ChunkManager class so you can see the lists I have
#pragma once
#include <iostream>
#include<list>
#include<vector>
#include "AbstractChunk.h"
#ifndef CHUNKMANAGER_H
#define CHUNKMANAGER_H
class ChunkManager
{
public:
ChunkManager();
ChunkManager(b2World *world);
~ChunkManager();
bool isChunkLoaded(int x, int y);
bool isChunkGenerated(int x, int y);
void loadChunksArround(int x, int y);
AbstractChunk* loadChunk(int x, int y);
int unloadChunk(int x, int y);
std::list<AbstractBlock>* getLoadedBlocks();
private:
b2World *world;
std::list<AbstractChunk> loadedChunks;
std::list<AbstractBlock> loadedBlocks;
AbstractChunk* generateChunk(int x, int y);
};
#endif
AbstractChunk.cpp:
#include "AbstractChunk.h"
AbstractChunk::AbstractChunk()
{
}
AbstractChunk::AbstractChunk(int x, int y){
xpos = x;
ypos = y;
}
int AbstractChunk::getXpos(){
return xpos;
}
AbstractChunk::~AbstractChunk()
{
}
AbstractBlock.cpp:
#include "AbstractBlock.h"
AbstractBlock::AbstractBlock()
{
}
AbstractBlock::AbstractBlock(int x, int y, float roation, b2World *world){
}
sf::Sprite AbstractBlock::draw(){
sf::Sprite sprite;
return sprite;
}
void AbstractBlock::destroy(b2World *world){
}
AbstractBlock::~AbstractBlock()
{
}
ChunkManager.cpp:
#include "ChunkManager.h"
ChunkManager::ChunkManager(){
}
//Ignore this, working on it now
void ChunkManager::destroy(){
for (int i = 0; i < loadedChunks.size; i++){
loadedChunks.
}
}
ChunkManager::ChunkManager(b2World *w){
AbstractChunk* chunk = generateChunk(0, 0);
loadedChunks.push_back(chunk);
for (int i = 0; i < 64; i++){
for (int p = 0; p < 64; p++){
if (std::rand() > .7){
AbstractBlock block(i, p, 0, w);
}
}
}
}
std::list<AbstractBlock>* ChunkManager::getLoadedBlocks(){
return &loadedBlocks;
}
ChunkManager::~ChunkManager()
{
}
AbstractChunk* ChunkManager::generateChunk(int x, int y){
if (!isChunkGenerated(x,y)){
AbstractChunk chunk(x, y);
return &chunk;
}
else
return nullptr;
}
bool ChunkManager::isChunkGenerated(int x, int y){
return false;
}
AbstractChunk* ChunkManager::loadChunk(int x, int y){
return nullptr;
}
void ChunkManager::loadChunksArround(int x, int y){
int chunkX = std::floor(x / 16);
int chunkY = std::floor(y / 16);
for (int i = -1; i < 2; i++){
for (int p = -1; p < 2; p++){
loadChunk(i, p);
}
}
}
Your code denotes some confusion on very fundamental concepts like value and identity in C++. For example in
AbstractChunk *chunk = generateChunk(0, 0);
seems that generateChunk will allocate an object on the free store.
Then however in:
loadedChunks.push_back(*chunk);
you are storing a copy of the allocated object in a container and the pointer is never used later (thus leaking the object).
Wildly guessing from the name, AbstractChunk is an abstract class with derived classes and the list should be an heterogeneous list of chunks of different types.
This is simply not possible in C++ (see the fundamental concepts of "slicing" and "copy semantic" of C++). You need to use a list of pointers to chunks instead.
Note that piling up a long stream of statements without understanding deeply how things works is a suicide strategy with C++. Even the fact that you assume that if you make a mistake the system will tell you so denotes you don't know how C++ works (see "undefined behavior" concept).
C++ cannot be learned by experimentation. You need to read a good book or two from cover to cover first.
There is no way to learn C++ except than by reading (and the smarter you are the worse the guessing approach will work... the reason is that in quite a few places the correct answer is not logical, but a consequence of an historic accident).

How to create a vector of class objects in C++?

I am trying to create a simple stack using vector in C++.
Here is the code:
#include <vector>
class Site
{
public:
int i; // site position i (x-axis)
int s; // site state
vector<Site> neighbors;
Site(void);
Site(int ii, int ss);
void AddNeighbor(Site &site);
};
Site::Site()
{
i = -1;
s = -1;
vector<Site> neighbors;
}
Site::Site(int ii, int ss)
{
i = ii;
s = ss;
}
void Site::AddNeighbor(Site &site)
{
neighbors.push_back(site);
}
void testStack()
{
int tot = 600;
vector<Site> myStack();
int i = 0;
while (i < tot)
{
Site site(i, 1);
myStack.push_back(site);
i++;
}
i = 0;
while (i < tot)
{
Site *site = myStack.back();
myStack.pop_back();
cout << site->i << site->s << endl;
i++;
}
}
Compiler errors:
ising_wolff.cpp: In function ‘void testStack()’:
ising_wolff.cpp:373:17: error: request for member ‘push_back’ in
‘myStack’, which is of non-class type ‘std::vector()’
myStack.push_back(site);
^ ising_wolff.cpp:380:30: error: request for member ‘back’ in ‘myStack’, which is of non-class type ‘std::vector()’
Site *site = myStack.back();
^ ising_wolff.cpp:381:17: error: request for member ‘pop_back’ in ‘myStack’, which is of non-class type
‘std::vector()’
myStack.pop_back();
What do these errors mean?
Here are some sites I have looked at:
1) Creating objects while adding them into vectors
2) push_back causing errors in C
3) how to create vectors of class object
How to create a vector of class objects in C++?
Start with something simpler so you can get the hang of it.
First, create a vector of primitive ints:
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> sites(5);
sites.push_back(5);
for(int x = 0; x < sites.size(); x++){
cout << sites[x];
}
cout << endl;
return 0;
}
Compiling it:
g++ -o test test.cpp
Running it:
./test
000005
Create a vector of class objects in a similar way as above:
#include <iostream>
#include <vector>
using namespace std;
class Site {
public:
int i;
};
int main() {
vector<Site> listofsites;
Site *s1 = new Site;
s1->i = 7;
Site *s2 = new Site;
s2->i = 9;
listofsites.push_back(*s1);
listofsites.push_back(*s2);
vector<Site>::iterator it;
for (it = listofsites.begin(); it != listofsites.end(); ++it) {
cout << it->i;
}
return 0;
}
Which should print:
79
vector<Site> myStack();
This is actually a function declaration. The function is called myStack and it returns a vector<Site>. What you actually want is:
vector<Site> myStack;
The type of neighbours at the moment will store copies of the objects, not references. If you really want to store references, I recommend using a std::reference_wrapper (rather than using pointers):
vector<reference_wrapper<Site>> neighbors;
vector<Site> myStack();
This is wrong. Lose the ().
You're declaring a function, not a vector.
Just write:
vector<Site> myStack;
You could use:
vector<Site> myStack;
myStack.resize(100); //will create 100 <Site> objects

Double function segmentation fault on return to double

I have a double function
double Grid::getAverageNeighborhoodFitnessEvaluation(int agentPositionX, int agentPositionY)
{
GetNeighbourhood(agentPositionX, agentPositionY,neighborhoodEvaluations);
int neighborscount = 0;
double fitnesssum = 0;
double neighborfitness;
double value;
for (size_t i = 0; i < neighborhoodEvaluations.size(); ++i)
{
if ((*(neighborhoodEvaluations.at(i))) != NULL)
{
neighborfitness = (*(neighborhoodEvaluations.at(i)))->GetFitness();
if(neighborfitness<0)
neighborfitness=0;
fitnesssum+=neighborfitness;
neighborscount++;
}
}
value = fitnesssum/neighborscount;
return value;
}
GetNeighbourhood assigns an array of a defined type (Agent) to neighborhoodEvaluations
*(neighborhoodEvaluations.at(i)))->GetFitness(); returns a double that represents a value for that point in the array. These have all been used previously with no issues.
When called from my main (where RealX and RealY are two integers)
int currentFitness = getAverageNeighborhoodFitnessEvaluation(RealX,RealY);
always works
double currentFitness = getAverageNeighborhoodFitnessEvaluation(RealX,RealY);
causes Segmentation fault
Does anyone know what possibilities could result in this and/or what value an int can take but a double can't seem to?
So far i have traced the error to our Agent implementation
Agent.cpp
#include "Agent.h"
Agent::Agent(void)
{
m_age = 0;
m_fitness = -1;
}
Agent::~Agent(void)
{
}
int Agent::GetAge()
{
return m_age;
}
double Agent::GetFitness()
{
return m_fitness;
}
void Agent::IncreaseAge()
{
m_age++;
}
AgentType Agent::GetType()
{
return m_type;
}
Agent.h
#ifndef AGENT_H
#define AGENT_H
enum AgentType { candidateSolution, cupid, reaper, breeder};
class Agent
{
public:
Agent(void);
virtual ~Agent(void);
double GetFitness();
int GetAge();
void IncreaseAge();
AgentType GetType();
virtual void RandomizeGenome() = 0;
protected:
double m_fitness;
AgentType m_type;
private:
int m_age;
};
#endif // !AGENT_H
Can't seem to locate the exact problem though
From your comment on the gdb debugger answer, I see that you are calling the GetFitness method on a null object (Agent::GetFitness (this=0x0)). This means that neighborhoodEvaluations.at(i) is returning a null-pointer. at() only checks for out of bounds, but if what was put into the array to begin with is a null pointer, at() won't help you. To guard agains this, you should change
if ((*(neighborhoodEvaluations.at(i))) != NULL)
into
if (neighborhoodEvaluations.at(i) != NULL)
If neighborhoodEvaluations is not supposed to contain null pointers, you will have to track down why getNeighborhood() is putting them there. Perhaps you are looking for out-of-bound neighbors for the elements at the edge of your set of points?
Quickly get started on gdb debugger using this article http://www.cs.cmu.edu/~gilpin/tutorial/ . Then tell us which line produces the segmentation fault .