Unhandled exception at 0x000FBA44 in Top Down Shooter - c++

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).

Related

C++ std::queue push pop two different objects gets first object

I have following program:
int main(){
std::queue<Stone> Q;
Stone s1=Stone(8,8);
s1.setStoneColor(Color::WHITE);
Q.push(s1);
Stone curr = Q.back();
Q.pop();
Stone s2=Stone(7,7);
s2.setStoneColor(Color::BLACK);
Q.push(s2); //here Q contains x=8,y=8,colour=WHITE...why??
Stone curr2 = Q.back();
Q.pop();
return 0 ;
}
why is in the Queue at the end White stone with coords (x,y)=(8,8) ?
I thought that objects are copied into Queue by value, so there are not any references/pointers.
I also thought that somehow I didnt specified destructor?
Could it be somehow remedied by using smart pointers?
I come from java background so these weird errors are baffling...
Thanks.
I'm using Clion IDE if it helps.
EDIT: I tried the same thing in Xcode and after pushing second stone there was expected 7,7,black...
I believe it is Clion/Cmake/Debugger thing, anyone knowledgable about these?
Classes I'm using are:
enum Color{
BLACK=0,
WHITE=1,
BLANK=2
};
and class
class Stone {
int x = 0;
int y = 0;
bool discovered = false;
Color stoneColor;
public:
Stone(int _x, int _y) {
this->x = _x;
this->y = _y;
this->stoneColor = Color::BLANK;
}
void setDiscovered(bool value){
discovered=value;
}
bool getDiscovered(){
return discovered;
}
//setter
void setStoneColor(Color _stoneColor) {
stoneColor = _stoneColor;
}
//getter
Color getStoneColor()const {
return stoneColor;
}
int getPositionX() const {
return x;
}
int getPositionY() const{
return y;
}
bool operator==(const Stone &other) const {
if(this->x==other.getPositionX()&&this->x==other.getPositionY()&& this->stoneColor==other.getStoneColor()){
return true;
}
else{
return false;
}
}
};
When you do the first Q.pop(), will'd expect Q to be empty at-least before the next push(). Don't know how or why it had white stones. But concerning why you thought the object are copied by value or maybe you felt they were instead copied by reference, in this case they are copied by value and if not for the Q.pop you should expect them to be there cus they were declared in the local scope inside main function and they should persist at-least within this scope except destroyed.

Getting Segmentation Error in code

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);
}

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 .

The OpenCV lib with c++ - in Detail cv::Mat::at causes SIGSEGV on large images

I am currently writing an application in c++ using the openCV-lib (version 2.1).
The task was to implement a small database as a students project, using some of the features of this library. My very own implementations of the median-filter and the boxcar-filter use the cv::Mat::at method to access single pixels in a given image with both reading and writing operations.
The curious thing about this is: It works just perfect on smaller images.
but only larger images it allways generates a SIGSEGV, allways on the same coordinates.
Is this a know bug or am i really doing something wrong?
here are the most significants functions i wrote:
class point {
public:
int x,y;
};
class ImageEntry {
friend class ImageDB;
private:
string _key;
string _filename;
Mat *_data;
ImageEntry* _next;
void show(void);
public:
void operator<<(ImageFilter* x);
~ImageEntry();
ImageEntry(string filename, string key);
Vec3b GetPoint(int x, int y);
point GetSize(void);
void SetPoint(int x, int y, Vec3b color);
};
point ImageEntry::GetSize(void) {
point iRet;
iRet.x = _data->cols;
iRet.y = _data->rows;
return iRet;
}
Vec3b ImageEntry::GetPoint(int x, int y) {
Vec3b iRet;
iRet = _data->at<Vec3b>(x,y);
return iRet;
}
void ImageEntry::SetPoint(int x, int y, Vec3b color) {
_data->at<Vec3b>(x,y) = color;
}
void MedianFilter::filterImage(ImageEntry* img) {
Vec3b Points[9];
Vec3b NewColor;
unsigned char ActChan[9];
point range = img->GetSize();
for (int act_x = 1; act_x < (range.x - 1); act_x++) {
for (int act_y = 1; act_y < range.y - 1; act_y++) {
Points[0] = img->GetPoint(act_x-1,act_y-1);
Points[1] = img->GetPoint(act_x,act_y-1);
Points[2] = img->GetPoint(act_x+1,act_y-1);
Points[3] = img->GetPoint(act_x-1,act_y);
Points[4] = img->GetPoint(act_x,act_y);
Points[5] = img->GetPoint(act_x+1,act_y);
Points[6] = img->GetPoint(act_x-1,act_y+1);
Points[7] = img->GetPoint(act_x,act_y+1);
Points[8] = img->GetPoint(act_x+1,act_y+1);
for (int act_color = 0; act_color < 3; act_color++) {
for (int i = 0; i < 9; i++) ActChan[i] = Points[i][act_color];
SelSort9(ActChan);
NewColor[act_color] = ActChan[4];
}
img->SetPoint(act_x,act_y,NewColor);
}
}
}
I would really appreciate any suggestion.
Thank you for your time!
If you take a look at the function at(), which you use in the SetPoint() method, in the documentation of OpenCv, it says:
template<typename _Tp> _Tp& Mat::at(int i, int j)
Return reference to the specified matrix element.
Parameters:
i – The 0-based row index
j – The 0-based column index
Furthermore, if you look at your GetSize() method, you set iRet.y = _data->rows and then in the method filterImage() use a for loop to loop from act_y = 1 to iRet.y. The second loop, loops through the rows. At the end of this method you call SetPoint(act_x, act_y), which on its turn calls at(act_x, act_y) basically.
Recall that act_y was an index of a row, but is now being used as index of a column. I hope this suggestion is all you need to solve your problem.

Can't return anything other than 1 or 0 from int function

I wish my first post wasn't so newbie. I've been working with openframeworks, so far so good, but as I'm new to programming I'm having a real headache returning the right value from an int function. I would like the int to increment up until the Boolean condition is met and then decrement to zero. The int is used to move through an array from beginning to end and then back. When I put the guts of the function into the method that I'm using the int in, everything works perfectly, but very messy and I wonder how computationally expensive it is to put there, it just seems that my syntactic abilities are lacking to do otherwise. Advice appreciated, and thanks in advance.
int testApp::updown(int j){
if(j==0){
arp =true;
}
else if (j==7){
arp = false;
}
if(arp == true){
j++;
}
else if(arp == false){
j--;
}
return (j);
}
and then its called like this in an audioRequest block of the library I'm working with:
for (int i = 0; i < bufferSize; i++){
if ((int)timer.phasor(sorSpeed)) {
z = updown(_j);
noteOut = notes [z];
cout<<arp;
cout<<z;
}
EDIT: For addition of some information. Removed the last condition of the second if statement, it was there because I was experiencing strange happenings where j would start walking off the end of the array.
Excerpt of testApp.h
int z, _j=0;
Boolean arp;
EDIT 2: I've revised this now, it works, apologies for asking something so rudimentary and with such terrible code to go with. I do appreciate the time that people have taken to comment here. Here are my revised .cpp and my .h files for your perusal. Thanks again.
#include "testApp.h"
#include <iostream>
using namespace std;
testApp::~testApp() {
}
void testApp::setup(){
sampleRate = 44100;
initialBufferSize = 1024;
//MidiIn.openPort();
//ofAddListener(MidiIn.newMessageEvent, this, &testApp::newMessage);
j = 0;
z= 0;
state = 1;
tuning = 440;
inputNote = 127;
octave = 4;
sorSpeed = 2;
freqOut = (tuning/32) * pow(2,(inputNote-69)/12);
finalOut = freqOut * octave;
notes[7] = finalOut+640;
notes[6] = finalOut+320;
notes[5] = finalOut+160;
notes[4] = finalOut+840;
notes[3] = finalOut+160;
notes[2] = finalOut+500;
notes[1] = finalOut+240;
notes[0] = finalOut;
ofSoundStreamSetup(2,0,this, sampleRate, initialBufferSize, 4);/* Call this last ! */
}
void testApp::update(){
}
void testApp::draw(){
}
int testApp::updown(int &_j){
int tmp;
if(_j==0){
arp = true;
}
else if(_j==7) {
arp = false;
}
if(arp == true){
_j++;
}
else if(arp == false){
_j--;
}
tmp = _j;
return (tmp);
}
void testApp::audioRequested (float * output, int bufferSize, int nChannels){
for (int i = 0; i < bufferSize; i++){
if ((int)timer.phasor(sorSpeed)) {
noteOut = notes [updown(z)];
}
mymix.stereo(mySine.sinewave(noteOut),outputs,0.5);
output[i*nChannels ] = outputs[0];
output[i*nChannels + 1] = outputs[1];
}
}
testApp.h
class testApp : public ofBaseApp{
public:
~testApp();/* destructor is very useful */
void setup();
void update();
void draw();
void keyPressed (int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
void newMessage(ofxMidiEventArgs &args);
ofxMidiIn MidiIn;
void audioRequested (float * input, int bufferSize, int nChannels); /* output method */
void audioReceived (float * input, int bufferSize, int nChannels); /* input method */
Boolean arp;
int initialBufferSize; /* buffer size */
int sampleRate;
int updown(int &intVar);
/* stick you maximilian stuff below */
double filtered,sample,outputs[2];
maxiFilter filter1;
ofxMaxiMix mymix;
ofxMaxiOsc sine1;
ofxMaxiSample beats,beat;
ofxMaxiOsc mySine,myOtherSine,timer;
int currentCount,lastCount,i,j,z,octave,sorSpeed,state;
double notes[8];
double noteOut,freqOut,tuning,finalOut,inputNote;
};
It's pretty hard to piece this all together. I do think you need to go back to basics a bit, but all the same I think I can explain what is going on.
You initialise _j to 0 and then never modify the value of _j.
You therefore call updown passing 0 as the parameter every time.
updown returns a value of 1 when the input is 0.
Perhaps you meant to pass z to updown when you call it, but I cannot be sure.
Are you really declaring global variables in your header file? That's not good. Try to use local variables and/or parameters as much as possible. Global variables are pretty evil, especially declared in the header file like that!