After changing my source output to a pointer, I started getting segfaults happening on calls to my GetOutput() function. I'm fairly certain I'm not initializing output correctly. Initializing it to NULL as I'm currently doing doesn't work, and I'm fairly certain it doesn't make sense either considering it would mean that output would never hold anything. It's also possible I'm just making a syntax mistake, I suppose. So I'd appreciate any ideas as to how I should initialize my output.
// source.c
#include <iostream>
#include <source.h>
#include <stdlib.h>
Source::Source()
{
Image * output = NULL;
output->SetSource(this);
}
Source::~Source() {}
Image * Source::GetOutput() const
{
std::cerr << "This function never executes due to segfault." << std::endl;
output->ResetSize(output->GetWidth(), output->GetHeight());
return output;
}
void Source::Update()
{
Execute();
}
// source.h
#include <image.h>
#ifndef SOURCE_H
#define SOURCE_H
class Image;
class Source
{
public:
Source();
virtual ~Source();
Image * GetOutput(void) const;
virtual void Execute()=0;
virtual void Update();
protected:
Image* output;
};
#endif
The below code first sets the pointer to NULL and then tries to use it, so of course there's an error.
Image * output = NULL;
output->SetSource(this);
Instead, you can initialise it by using the new keyword, like so:
Image *output = new Image;
output->SetSource(this);
Related
Passing an array of objects to a function is not giving back the desired values set in the settingUp function.
Try to print the values stored in the first item of the array in the main function.
main.ccp:
//** Libraries included **//
using namespace std;
//#include "common.h"
#include "settingUp.h"
int main(){
statusClass status[5];
//** Main Functions **//
settingUp(status);
status[1].printValues();
}
settings.h:
#ifndef settingUp_h
#define settingUp_h
//** Libraries **//
#include "statusClass.h"
#include <stdio.h>
#include "dataClass.h"
void settingUp(statusClass *_status);
#endif
settings.ccp //UPDATE: few lines corrected!
//** Libraries **//
#include "settingUp.h"
//** Status classes and their functions **//
void settingUp(statusClass *_status){
//statusClass statusProv;
dataClass * prueba0 = new dataClass(); //Corrected!
dataClass * prueba1 = new dataClass(); //Corrected!
dataClass * prueba2 = new dataClass(); //Corrected!
const dataClass * arrayPrueba[3];
prueba0.setValues(1);
prueba1.setValues(2);
prueba2.setValues(3);
arrayPrueba[0] = prueba0; //Corrected!
arrayPrueba[1] = prueba1; //Corrected!
arrayPrueba[2] = prueba2; //Corrected!
_status[1].setValues(1, arrayPrueba);
//_status = &statusProv;
_status[0].printValues();
}
UPDATE:
statusClass.cpp:
//** Libraries **//
#include "statusClass.h"
//** Status classes and their functions **//
void statusClass::setValues (uint8_t _statusSelectorByte, const dataClass **_array){
newStatusSelectorByte = _statusSelectorByte;
array = _array;
};
void statusClass::printValues(){
printf("TP: statusClass -> printValues: Prueba = %d\n", newStatusSelectorByte);
printf("TP: statusClass -> printValues: arrayPrueba = %d\n", array[1]->length);
}
printValues() in the settingUp() gives the right values, not in main.cpp.
Update: for array[0]->length works, for array[2]->length does not work.
When you do the following:
dataClass prueba0;
you create an object on the stack. This object is valid until you exit that function.
One solution is to allocate that object:
dataClass * prueba0 = new dataClass();
That means at some point you'll need to delete the object with:
delete prueba0;
To avoid having to use delete, you should look into using shared pointers.
I think your next problem is that in main you have:
statusClass status[5];
So 5 different status objects.
Then inside the initialization function, you specifically initialize _status[1]:
_status[1].setValues(1, arrayPrueba);
In other words, your _status[0] access within the initialization is going to show the random values that were on the stack when entering main() (which by luck are zeroes by default).
Maybe you are thinking that:
array = _array;
copies the values from one array to another. Right now, all that does is save a pointer. The array on the left is the pointer you created named arrayPrueba.
I just don't think you understand your code much and to tell you the truth, you should be using std::vector instead of C arrays. If you really want to write C++ code, learn the standard library (STL).
Okay, I may be doing this wrong, but I am at my wits end.
I have a vector of shared_ptr of my node class that I pass around for various things, my node class has a vector of share_ptr of it neighbors of type node.
I have a class that generates the mesh of nodes for me, and returns a std::vector<std::shared_ptr<Node>> nodes, and a significant std::shared_ptr<Node> significant node.
I then pass this vector into an indexer that creates a second list that is a subset of the first of about 10% the size, which it returns as std::vector<std::shared_ptr<Node>> indexedNodes.
After these are created, I pass them into another object that keeps them for later reference.
Then a modifier class gets the a single random node from the indexedNodes, and uses that to walk through the node neighbors modifying a height value.
Later, when I go to export these out, the values show up as 0/initialized.
Somethings to note, I pass the data into the functions and return with just std::vector<std::shared_ptr<Node>> which I figured is my issue, I am just not sure how to properly pass a container of my shared_ptr so that I don't make copies.
If more info is needed, let me know. I am looking for an example or a reference that I can understand.
Sorry for the code, it is not beautful, and I have it using Dynamically Loaded Libraries.
The function where the work is done:
void cruthu::Cruthu::Run() {
std::shared_ptr<cruthu::ITeraGen> teraGen(this->mSettings.TeraGen.Factory->DLGetInstance());
std::vector<std::shared_ptr<cruthu::Node>> nodes(teraGen->Create());
std::shared_ptr<cruthu::Node> significantNode(teraGen->GetSignificantNode());
std::vector<std::shared_ptr<cruthu::IIndexer>> indexers;
for(const auto indexer : this->mSettings.Indexers) {
indexers.push_back(indexer.Factory->DLGetInstance());
}
std::vector<std::shared_ptr<cruthu::Node>> indexedNodes(indexers.at(0)->Index(nodes));
std::shared_ptr<cruthu::ITera> tera(this->mSettings.Tera.Factory->DLGetInstance());
tera->SetNodes(nodes);
tera->SetIndexedNodes(indexedNodes);
tera->SetSignificantNode(significantNode);
for(const auto & formaF : this->mSettings.Formas) {
std::shared_ptr<cruthu::IForma> forma(formaF.Factory->DLGetInstance());
forma->SetNode(tera->GetIndexedNode());
forma->Modify();
std::cout << std::to_string(tera->GetIndexedNode()->GetHeight()) << std::endl;
}
this->CreateImage(tera);
}
TeraGen:
#ifndef CRUTHU_ITERAGEN_HPP
#define CRUTHU_ITERAGEN_HPP
#include <cruthu/Node.hpp>
#include <vector>
namespace cruthu {
class ITeraGen {
public:
virtual ~ITeraGen() = default;
virtual std::vector<std::shared_ptr<cruthu::Node>> Create() = 0;
virtual std::shared_ptr<cruthu::Node> GetSignificantNode() = 0;
};
} // namespace cruthu
#endif
Tera:
#ifndef CRUTHU_ITERA_HPP
#define CRUTHU_ITERA_HPP
#include <cruthu/IIndexer.hpp>
#include <cruthu/Node.hpp>
#include <memory>
#include <vector>
namespace cruthu {
class ITera {
public:
virtual ~ITera() = default;
virtual void SetNodes(std::vector<std::shared_ptr<cruthu::Node>>& nodes) = 0;
virtual void SetIndexedNodes(std::vector<std::shared_ptr<cruthu::Node>>& indexedNodes) = 0;
virtual void SetSignificantNode(std::shared_ptr<cruthu::Node> significantNode) = 0;
virtual std::vector<std::shared_ptr<cruthu::Node>>& GetNodes() = 0;
virtual std::vector<std::shared_ptr<cruthu::Node>>& GetIndexedNodes() = 0;
virtual std::shared_ptr<cruthu::Node> GetIndexedNode() = 0;
};
} // namespace cruthu
#endif
Indexer:
#ifndef CRUTHU_IINDEXER_HPP
#define CRUTHU_IINDEXER_HPP
#include <cruthu/Node.hpp>
#include <memory>
#include <vector>
namespace cruthu {
class IIndexer {
public:
virtual ~IIndexer() = default;
virtual std::vector<std::shared_ptr<cruthu::Node>> Index(std::shared_ptr<cruthu::Node> node) = 0;
virtual std::vector<std::shared_ptr<cruthu::Node>> Index(std::vector<std::shared_ptr<cruthu::Node>>& nodes) = 0;
};
} // namespace cruthu
#endif
Forma:
#ifndef CRUTHU_IFORMA_HPP
#define CRUTHU_IFORMA_HPP
#include <cruthu/Node.hpp>
namespace cruthu {
class IForma {
public:
virtual ~IForma() = default;
virtual void SetNode(std::shared_ptr<cruthu::Node> node) = 0;
virtual void Modify() = 0;
};
} // namespace cruthu
#endif
I did update and try adding references in in between, which is why they now have references in places. I still have the same issue.
As user Remy Lebeau stated please provide a minimal, complete and verifiable example.
As you stated you are passing a std::vector<std::shared_ptr<Node>> around from one class to another or from one function to another and that they are not updating and are 0 initialized. From the behavior that you are describing I then have a question for you, I'm posting this as an answer as it would be too long for a comment.
Does your function declaration/definition that accepts the vector or shared pointers above look something like this:
void someFunc( std::vector<shared_ptr<Node> nodes ) { ... }
or does it look something like this:
void someFunc( std::vector<shared_ptr<Node>& nodes ) { ... }
I ask this because it makes a difference if you are passing the container around by value as opposed to by reference.
This is not (yet) a answer, but questions to pin down the problem, since not enough implementation is provided.
One possible problem (hard to say without seeing the implementation...) is that you create the nodes in top of the Run() function:
std::vector<std::shared_ptr<cruthu::Node>> nodes(teraGen->Create());
Then you pass that function as reference in this call:
tera->SetNodes(nodes);
What does tera do with the nodes? Passing by reference means that the count of the shared_ptr:s isn't incremented.
what does this->CreateImage(tera) do?
Are the nodes used after Run() has finished?
I could not get it going with the comments from above, this is mainly my problem of not being able to provide adequate information.
With that said, I re-worked the code to instead pass a cruthu::Tera object around as a shared pointer and exposed the vectors as public members of the class. This is something I will revisit at a later date, as this implementation is not something I feel happy about.
The code is on github, unfortunately it is my thesis work, so I could no longer wait.
If people feel the desire to still attempt an answer, I will work with them.
I'm working on one of assignments to do with image manipulation (blending and zooming) and I've ran into a problem that I have hard time overcoming.
Structure of my application
Class Image
rgb struct: contains floats (they're flattened pixels) and overloaded operators.
pixels: a 1d array of pixels which is initialized via constructor to be h * w
Class destructor.
Destructor looks a little like this...
virtual ~Image()
{
if (pixels != NULL)
delete[] pixels;
}
Now I'm using another class called Filter which inherits from Image
class Filter: public class Image
std::vector of Image imgStack; Container for images that I'm going to blend
std::vector of Rgb pixelBuffer; A container for the pixels for each images one pixel. This is not dynamic so I'm not worried about deleting this.
Destructor for the derived class.
~Blend()
{
delete &imageStack;
}
what this part of my main.cpp looks like...
while (userInput != 5)
{
switch(userInput)
case 1:
{
Blend *meanImage = new Blend(3263, 2505, 13);
meanImage->writePPM("Mean_" + std::to_string(count) + ".ppm");//every iteration, the file name is unique
meanImage->~Blend();
}
}
In my main.cpp I'm basically running 13 images into the Blend object which stores the images in the vector container to do all my functionality on. During the run time the space used is around 1.3GB, but since my object is in a loop (i have a menu for multiple functionality) the object doesn't usually leave the scope so the destructor isn't automatically called, so I call it manually like this; medianImage->~Blend(); Now the all the error says is that my application "has triggered a breakpoint" and that's it... Note, no breakpoint is found anywhere. I'm aware that it's generally bad to use dynamic arrays because it causes all sorts of memory problems (if it's done by me), but I want to fix this just so I know how to solve these in the future.
If you have any questions of the code, I can post snippers.
Edit: here's an my Blend class.
#pragma once
#include "stdafx.h"
#include "Image.h"
#include <vector>
#include <string>
class Blend : public Image
{
private:
std::vector<Image> imageStack;
std::vector<Rgb*> pixelBuffer;//only works with pointers (no copying)
int m_noOfImages;
Rgb* getMedianFromSet();
Rgb getMeanFromSet();
Rgb getStdDev(Rgb meanPix);
public:
Blend(int width = 0, int height = 0, int noOfImages = 0):Image(width, height), m_noOfImages(noOfImages), imageStack(noOfImages), pixelBuffer(noOfImages)
{}
public:
void stack(bool push = true);
void meanBlend();
void medianBlend();
void sigmaClipping(float sigma = 0.5f);
~Blend()
{
delete &imageStack;
}
};
#pragma once
#include "stdafx.h"
#include "Image.h"
#include <vector>
#include <string>
#include <memory>
class Blend : public Image
{
private:
std::vector<Image> imageStack;
// Changed to shared_ptr<T> could use unique_ptr<T> depending on need.
std::vector<std::shared_ptr<Rgb>> pixelBuffer;//only works with pointers (no copying)
int m_noOfImages;
Rgb* getMedianFromSet();
Rgb getMeanFromSet();
Rgb getStdDev(Rgb meanPix);
public:
Blend(int width = 0, int height = 0, int noOfImages = 0):Image(width, height), m_noOfImages(noOfImages), imageStack(noOfImages), pixelBuffer(noOfImages)
{}
public:
void stack(bool push = true);
void meanBlend();
void medianBlend();
void sigmaClipping(float sigma = 0.5f);
// Clear Entire Buffer
void cleanup() {
// When using the heap with smart pointers
for ( auto item : containerVariable ) {
item.reset();
item = nullptr;
}
containerVariable.clear();
}
// Remove Single Element
void remove( unsigned idx ) {
// Write function to remove a single element from vector
}
~Blend()
{
// This is definitely wrong here: You are trying to delete a reference
// to a template container that is storing `Image` objects that
// are on the stack.
// delete &imageStack;
}
};
It is better to write a function to clean up memory, and to remove specific elements from containers when using dynamic memory than it is to use a class's destructor.
I really need help on this one cause I am extremely stuck and have no idea what to do.
Edit:
A lot of you guys are saying that I need to use the debugger but let me be clear I have not used C++ for an extremely long time and I've used visual studio for a grand total of 2 weeks so I do not know all the cool stuff it can do with the debugger.
I am a student at university at the beginning of my second year who is trying to work out how to do something mostly by failing.
I AM NOT a professional coder and I don't have all the knowledge that you people have when it comes to these issues and that is why I am asking this question. I am trying my best to show my issue so yes my code contains a lot of errors as I only have a very basic understanding of a lot of C++ principles so can you please keep that in mind when commenting
I'm only posting this here because I can don't know who else to ask right now.
I have a function called world that is suppose to call my render class to draw all the objects inside of its vector to the screen.
#include "C_World.h"
C_World::C_World()
{
// creates an instance of the renderer class to render any drawable objects
C_Renderer *render = new C_Renderer;
}
C_World::~C_World()
{
delete[] render;
}
// adds an object to the world vector
void C_World::addToWorld(C_renderable* a)
{
world_list.push_back(a);
}
void C_World::World_Update()
{
render->ClearScreen();
World_Render();
}
void C_World::World_Render() {
for (int i = 0; i < 1; i++)
{
//render->DrawSprite(world_list[i]->getTexture(), world_list[i]->get_X, world_list[i]->get_Y());
render->DrawSprite(1, 1, 1);
}
}
While testing I commented out the Sprites get functions in order to check if they were causing the issue.
the renderer sprites are added to the vector list in the constructor through the create sprite function
C_Renderer::C_Renderer()
{
// test sprite: Id = 1
CreateSprite("WhiteBlock.png", 250, 250, 1);
}
I thought this might of been the issue so I had it in other functions but this didn't solve anything
Here are the Draw and create Sprite functions
// Creates a sprite that is stored in the SpriteList
// Sprites in the spriteList can be used in the drawSprite function
void C_Renderer::CreateSprite(std::string texture_name,
unsigned int Texture_Width, unsigned int Texture_height, int spriteId)
{
C_Sprite *a = new C_Sprite(texture_name,Texture_Width,
Texture_height,spriteId);
SpriteList.push_back(a);
size_t b = SpriteList.size();
HAPI.DebugText(std::to_string(b));
}
// Draws a sprite to the X and Y co-ordinates
void C_Renderer::DrawSprite(int id,int x,int y)
{
Blit(screen, _screenWidth, SpriteList[id]->get_Texture(),
SpriteList[id]->getTexture_W(), SpriteList[id]->getTexture_H(), x, y);
}
I even added some test code into the create sprite function to check to see if the sprite was being added too the vector list. It returns 1 so I assume it is.
Exception thrown: read access violation.
std::_Vector_alloc<std::_Vec_base_types<C_Sprite *,
std::allocator<C_Sprite *> > >::_Mylast(...) returned 0x8.
that is the full error that I get from the compiler
I'm really really stuck if there is anymore information you need just say and ill post it straight away
Edit 2:
#pragma once
#include <HAPI_lib.h>
#include <vector>
#include <iostream>
#include "C_renderable.h"
#include "C_Renderer.h"
class C_World
{
public:
C_World();
~C_World();
C_Renderer *render = nullptr;
void World_Update();
void addToWorld(C_renderable* a);
private:
std::vector<C_renderable*> world_list;
void C_World::World_Render();
};
#pragma once
#include <HAPI_lib.h>
#include "C_renderable.h"
#include "C_Sprite.h"
#include <vector>
class C_Renderer
{
public:
C_Renderer();
~C_Renderer();
// gets a pointer to the top left of screen
BYTE *screen = HAPI.GetScreenPointer();
void Blit(BYTE *destination, unsigned int destWidth,
BYTE *source, unsigned int sourceWidth, unsigned int sourceHeight,
int posX, int posY);
void C_Renderer::BlitBackground(BYTE *destination,
unsigned int destWidth, unsigned int destHeight, BYTE *source,
unsigned int sourceWidth, unsigned int sourceHeight);
void SetPixel(unsigned int x,
unsigned int y, HAPI_TColour col,BYTE *screen, unsigned int width);
unsigned int _screenWidth = 1750;
void CreateSprite(std::string texture_name,
unsigned int Texture_Width,unsigned int Texture_height, int spriteId);
void DrawSprite(int id, int x, int y);
void ClearScreen();
private:
std::vector<C_Sprite*> SpriteList;
};
I don't say this lightly, but the code you've shown is absolutely terrible. You need to stop and go back several levels in your understanding of C++.
In all likeliness, your crash is the result of a simple "shadowing" issue in one or more of your functions:
C_World::C_World()
{
// creates an instance of the renderer class to render any drawable objects
C_Renderer *render = new C_Renderer;
}
C_World::~C_World()
{
delete[] render;
}
There are multiple things wrong here, and you don't show the definition of C_World but if this code compiles we can deduce that it has a member render, and you have fallen into a common trap.
C_Renderer *render = new C_Renderer;
Because this line starts with a type this is a definition of a new, local variable, render. Your compiler should be warning you that this shadows the class-scope variable of the same name.
What these lines of code
C_World::C_World()
{
// creates an instance of the renderer class to render any drawable objects
C_Renderer *render = new C_Renderer;
}
do is:
. assign an undefined value to `this->render`,
. create a *local* variable `render`,
. construct a dynamic `C_Renderer` presumably on the heap,
. assign that to the *local* variable `render`,
. exit the function discarding the value of `render`.
So at this point the memory is no-longer being tracked, it has been leaked, and this->render is pointing to an undefined value.
You repeat this problem in several of your functions, assigning new results to local variables and doing nothing with them. It may not be this specific instance of the issue that's causing the problem.
Your next problem is a mismatch of new/delete vs new[]/delete[]:
C_World::~C_World()
{
delete[] render;
}
this would result in undefined behavior: this->render is undefined, and delete[] on a non-new[] allocation is undefined.
Most programmers use a naming convention that distinguishes a member variable from a local variable. Two common practices are an m_ prefix or an _ suffix for members, e.g.
class C_World
{
public:
C_Foo* m_foo; // option a
C_Renderer* render_; // option b
// ...
}
Perhaps you should consider using modern C++'s concept of smart pointers:
#include <memory>
class C_World {
// ...
std::unique_ptr<C_Renderer> render_;
// ...
};
C_World::C_World()
: render_(new C_Renderer) // initializer list
{}
But it's unclear why you are using a dynamic allocation here in the first place. It seems like an instance member would be better:
class C_World {
C_Renderer render_;
};
C_World::C_World() : render_() {}
I created simple code in MVS2010 but it doesn't work.
There is just a class with header file and main.
Could you tell me what is wrong?
Main:
#include <iostream>
#include "Developer.h"
int main() {
Developer xx("asd", "sfdasdf", "asdsa");
std::cout << xx.Dev_ID;
char c;
std::cin >> c;
return 0;
}
Header:
class Developer {
public:
char * Dev_ID;
char * Dev_Name;
char * ApplicationType;
char * Name_Application;
public:
Developer(char * name, char * appType, char * appName);
void create();
void edit();
void remove();
};
Class:
#include "Developer.h"
Developer::Developer(char * name, char * appType, char * appName){}
void Developer::create(){}
void Developer::edit(){}
void Developer::remove(){}
You need to add a semicolon ';' after the class definition.
The definition of member function should be of the form returnType ClassName::FunctionName(args).
void Developer::create(){}
void Developer::edit(){}
void Developer::remove(){}
Also, you don't need a semi color after the #include directives. I would suggest going through a C++ basics book and try out the examples to get a hold of the language!
When I run my app it gives an unhandled exceptions and crashes...
Of course it does. Your constructor doesn't fill in any of the member variables. So xx.Dev_ID is undefined; it contains random garbage. When you attempt to std::cout random garbage, the program rightly crashes.
You probably intend to initialize Dev_ID to some value. You need to do that in the constructor. That's what the constructor is for: initializing member variables.
As Chethan stated, you need to look through some basic C++ books.