pointer being freed was not allocated (suspected due to double deletion) [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Every time I try to delete an object in my array of pointers plantLayout[][], I get the error "pointer being freed was not allocated". I debugged it and realized that every time that I step into the ~Plant() destructor it goes into the malloc files and then back to the ~Plant() destructor, and then back into the malloc files, and then it gets that error. I am assuming that it is because of a double deletion error, but I can not seem to figure out where I am going wrong.
Below is the relevant code:
MainWindow.h: (relevant code)
const static int rows = 5;
const static int columns = 10;
Plant *plantLayout[rows][columns-1];
Plant *seedingPlant;
Plant.h
#ifndef PLANT_H
#define PLANT_H
#include <QString>
#include <QGraphicsPixmapItem>
#include <sun.h>
class Plant
{
public:
Plant();
int x, y;//top left corner of the plant's lawn piece
int width, height;//of lawn piece
int plant, cost, life, range, damage, splash, slow, bomb, sun, need, row, column;
static int statCost;
double rate, seeding;
QString name;
QGraphicsPixmapItem *icon;
QString file;
Sun sunObject;
bool active;
virtual void beginAttackingSequence();
virtual void explosion();
};
#endif // PLANT_H
Plant.cpp
Plant::Plant()
{
this->sun = 0;
this->active = false;
this->height = 60;
this->width = 60;
this->sunObject.onScreen = false;
}
void Plant::beginAttackingSequence(){
}
void Plant::explosion(){
}
I assign the set the seeding plant equal to a new SunFlower() which is a subclass of Plant
seedingPlant = new SunFlower();
and then later on I assign a certain element of the plantLayout[][] array to the seedingPlant.
plantLayout[r][c] = seedingPlant;
at later points in the program I reinitialize the seedingPlant to be another different subclass of the Plant.
if(plantLayout[r][c] != NULL){
delete plantLayout[r][c];
}
I checked if that element is equal to null, which is what lead me to believe that it was a double delete that was causing the error!
Any help would be greatly appreciated! Thanks in advance!

You don't have all of the code posted, but a few things I can suggest:
You mentioned that SunFlower is a subclass of Plant. If you have polymorphic inheritance, you always want to have a virtual destructor (see C++ FAQ 20.7 for more info). In your case, add the following to the Plant declaration:
virtual ~Plant();
and add an implementation for it in Plant.cpp:
Plant::~Plant()
{
}
You're checking for NULL before invoking delete. You do not need to do that (and it's considered bad style). delete plantLayout[r][c]; by itself is just fine. See C++ FAQ 16.8 for more info.
Ensure that plantLayout is initialized to 0. e.g., in the constructor for MainWindow, you'll probably want:
for (int r = 0; r < rows; ++r)
for (int c = 0; c < columns-1; ++c)
plantLayout[r][c] = NULL;
My suspicion is that the "pointer being freed was not allocated" error is due to you invoking delete plantLayout[r][c] when plantLayout[r][c] is uninitialized (so it may contain some seemingly random value).

Related

C++ successive checks of object variable value yield different results? [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
I am new to C++, though I have worked with C and Java before.
In the following code, I:
Define the polygon class. For now it only has 1 variable: numpoints
create a global pointer to a polygon object that's null
define a handler for a click event, which if the object exists, just prints the value of numpoints. If it doesn't, it creates it and sets the value of numpoints to be 0.
//defining polygon class
class polygon{
public:
int numpoints;
};
//create a global pointer that's uninitialized
static polygon *current = NULL;
//define a click handler.
void leftClick(int x, int y){
if (current==NULL){
polygon newpoly;
current = &newpoly;
current->numpoints = 0;
printf("created new polygon\n");
printf("%i points\n", (*current).numpoints);
}else{
printf("polygon exists\n");
printf("%i points\n", (*current).numpoints);
}
}
After the first click, the program prints
created new polygon
0 points
as expected. However, after the second and subsequent clicks, it prints
polygon exists
-1567658064 points
Or some other seemingly random number. Anybody know what is going on here? Why is the value not staying at 0? Any help is appreciated.
This should work:
//defining polygon class
class polygon{
public:
int numpoints;
};
//create a global pointer that's uninitialized
static polygon *current = NULL;
polygon newpoly;
//define a click handler.
void leftClick(int x, int y){
if (current==NULL){
current = &newpoly;
current->numpoints = 0;
printf("created new polygon\n");
printf("%i points\n", (*current).numpoints);
}else{
printf("polygon exists\n");
printf("%i points\n", (*current).numpoints);
}
}
The problem is that newpoly is destroyed after the first printf because it goes out of scope. You have to learn how memory is managed in C++.
newpoly is a local variable. You are taking its address but it is destroyed right after so that address doesn't make sens anymore.
What you could do is use dynamic allocation instead : current = new polygon;.
But it is generally bad to use dynamic allocation without wrapping it in some way.
If you are using C++11, you can use a std::unique_ptr<polygon> from the header <memory>.
The result is
static std::unique_ptr<polygon> current; // No need to set it to NULL
...
current.reset(new polygon);
This changes will ensure that your allocation is properly deleted when needed.

how to accessing vectors in a loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am programming a Space Invaders clone and I am struggling at creating the bullets.
Whenever I click Space a bullet is supposed to be added to the vector and then I want to move them via a loop, but I dont understand how to create and handle it the proper way.
vector<Bullet> bullets(MAXBULLETS);
int bulletcounter = 0;
while (1) {
Sleep(10);
for (int i = 0; i < sizeof(bullets)-1; i++) {
bullets[i].Move(0, 1);
}
if (GetAsyncKeyState(VK_SPACE)) {
Bullet *bullet = new Bullet();
bullets[bulletcounter] = bullet; // Here is the error
bulletcounter++;
}
bullets is a vector that holds objects of type Bullet.
Bullet *bullet = new Bullet();
bullets[bulletcounter] = bullet; // Here is the error
Your bullet here is of type Bullet*. The two incompatible types get you the error.
To fix this, stop using a pointer and just instantiate an object:
Bullet bullet;
This creates a Bullet object using the parameterless constructor that you can then add to your bullets.
Do note though, that this currently does nothing since you initialize your vector giving it a predefined size bullets(MAXBULLETS), this already creates MAXBULLETS default constructed objects for you, ready to use:
Constructs the container with count default-inserted instances of T.
No copies are made.
Side note : stop using new altogether; this isn't Java or C#. If you need a dynamically allocated object then use a smart pointer. Most of the time, though, an object automatic-storage duration will do just fine.
My proposal
vector<Bullet> bullets;
while (1)
{
Sleep(10);
for (int i = 0; i < bullets.size(); i++)
{
bullets[i].Move(0, 1);
}
if (GetAsyncKeyState(VK_SPACE))
{
bullets.push_back(Bullet());
}

How to implement a dynamic array of object pointers? "expression must be a modifiable lvalue"

I'm a c++ student and this is my second post here. I'm working on a class whose job is to maintain an array of object pointers. (That way a pointer can be passed in and added to the array, instead of the entire object.)
The array is supposed to be dynamic but I'm running into some errors when I try to dynamically allocate memory for it. The following code produces the error "expression must be a modifiable lvalue" at studArray, as marked.
#ifndef MYCLASS_H
#define MYCLASS_H
#include "Student.h"
class myClass{
private:
Student* studArray[5];
int howMany;
int max;
public:
myClass(){
Student firstOne;
studArray[0] = &firstOne;
howMany=0;
max=5;
}//myClass()
void insertEl( Student* nextEl ){
howMany++;
if(howMany >= max){
Student** tempPt = new Student* [max + 1];
for( int i = 0; i < currentNum; i++){
tempPt[i] = studArray[i];
}
delete [] studArray;
studArray = tempPt; // <-------------------------error
}
studArray[ howMany ] = nextEl;
}//insertEl
};
I tried changing the original Student * array to have no size specified, but that produced the error "incomplete type is not allowed" at studArray.
class myClass{
private:
Student* studArray[]; <------------- error
int howMany;
int max;
What am I doing wrong?
(Thank you for the help!)
For reference I'm using Win 7 64bit, Visual Studio Professional 2012.
Assumptions: Instructor want you to learn the fine art of memory management on your own. So no library containers and no smart pointers. When you have the time, look into how to use the standard containers and the smart pointers. They'll save you a huge amount of time and grief in the future.
First, declaring the Student array.
Student* studArray[5];
You have the crux of it right here
Student** tempPt = new Student* [max + 1];
So try
Student** studArray;
And then hack your constructor to allocate the storage
myClass()
{
max = 5;
studArray = new Student*[max]; /* For improved safety, read up on
exceptions, catch and handle the
out of memory exception */
howMany = 0;
} //myClass()
I recommend adding a destructor to handle the clean up and put back your array.
virtual ~myClass()
{
delete[] studArray;
}
Check with the assignment notes or the instructor to see who is responsible maintaining the Students. You may have to revisit the destructor to delete all of the Students before deleting studArray
Additional note:
myClass()
{
Student firstOne;
studArray[0] = &firstOne;
howMany=0;
max=5;
}//myClass()
Student firstOne; is a temporary variable. firstOne only exists between the closest enclosing {} braces. This is called Scope. Using any value outside of it's scope will have unpredictable results and most likely crash the program. Frankly, that's if you are lucky. The program may limp on for some indeterminate time and crash later.
The assignment studArray[0] = &firstOne; is dangerous because by the time anyone tries to use studArray[0], the data at which it points will not be valid. firstOnedoes not exist outside the constructor. If you want firstOne to go on living, you will have to define it as a pointer, create it with new, and delete it when it is no longer needed. In this case I don't think you ever need it.
Another suggestion is to double the size of studArray rather then simply adding one when it is full. This way you don't have to reallocate the storage and copy all of the existing students to the new storage as often.
A better method is to have a std::vector of Student:
std::vector<Student *> maleStuds;
std::vector<Student *> femaleStuds;
Or, if you must use arrays:
const unsigned int MAXIMUM_STUDENTS = 5;
Student * students[MAXIMUM_STUDENTS];
For dynamic:
Student * * students = new Student * [MAXIMUM_STUDENTS];

dynamic allocation and polymorphism - c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Need some insight on how to complete this last part of my Marina class. Any help would be greatly appreciated.
This is a big project I'm working on. I created a group of classes that are derived from a base class Boat using public inheritance. The Marina class represents the care of the boats in a Marina. The Marina class contains a fixed size array of pointers to Boat.
The function should place a new Boat into the Marina if there is room and each new boat must be dynamically allocated. The function should also ask the user what kind of boat they want and then add that kind to the next empty place in the array.
The error suggests that you forgot to include Boat.h (or anything defining class Boat) in your cpp file.
But anyway, code shown in question has some problems :
line _m[i] = NULL; is outside of the loop where i is declared and will raise an error - and I cannot imagine a reason to have it there ...
you create an uninitialized boat, and do not keep a pointer to it : how will you find and initialize it ?
You said that boats should be dynamically initialized, and that method _add_boat must be void. IMHO there are only two acceptable ways :
create the boat outside of the method and only use add_boat to put it in marina (throwing exception if marina if full) :
void Marina::_add_boat(Boat *boat)
{
for (unsigned i = 0; i < _num_boats; i++)
{
if (_m[i] == NULL)
_m[i] = boat;
return;
}
throw std::runtime_error("Marina full");
}
usage :
Boat b = new Boat();
marina._add_boat(b);
pass arguments to initialize boat
void Marina::_add_boat(int type, Owner& owner, ...) // arguments for Boat ctor
{
for (unsigned i = 0; i < _num_boats; i++)
{
if (_m[i] == NULL)
_m[i] = new Boat(type, owner, ...);
return;
}
throw std::runtime_error("Marina full");
}
Below is original answer left only because some interesting comments refere to it
Why not something like :
I assume you have an array of boats (Boat *) in the Marina of size _num_boats. An empty place is conventionnaly a NULL. It gives :
static const unsigned int _num_boats = 100; // the value you need or a constexpr
class Marina {
Boat * boats[_num_boats];
...
Boat * Marina::_add_boat() {
for (unsigned i=0; i<_num_boats; i++) {
if (boats[i] == NULL) {
boats[i] = new Boat();
return boats[i]; // returns dynamically created Boat if room in Marina
}
}
return NULL; // return NULL if Marina full
}
}
With this logic you set attributes of Boat after placing it in Marina ...

destructor is called continuesly [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I'm currently working on a game using OpenGL ES 2.0 on Android (in C++ using the NDK).
I have a class called "Drawable" which is my base class for drawing objects using OpenGL.
In the destructor of the class I have to clean up some buffers :
Drawable::~Drawable() {
LOGE("release");
releaseBuffers();
}
But the destructor is called endlessly (as in every loop of the thread), which messes up my drawing.
I'm kind of lost here and I could not find similar problems, so help is welcome!
Edit: Loop code is here : link
Edit2: I found one of the evil calls:
In my player class I have this call:
currentWeapon->draw(this);
to
void Weapon::draw(Player* p)
If I comment this, the spam is gone.
There are very few ways a destructor gets called:
1) You create an instance of Drawable on the stack, and it falls out of scope. If this is done in a tight loop, the object will fall out of scope and be destroyed at each iteration of the loop. For example:
for (size_t i = 0; i < 100; ++i)
{
Drawable d;
}
Here, 100 instances of Drawable will be created and destroyed, at the beginning and end of every loop.
2) You delete a dynamically-allocated Drawable:
for (size_t i = 0; i < 100; ++i)
{
Drawable* d = new Drawable;
delete drawable;
}
3) You call the destructor explicitly:
Drawable* b = new (buffer) Drawable;
b->~Drawable()
Note that #3 uses "placement new" and is highly unlikely.
Objects can be destroyed at suprising times when they are in a container such as a vector. Consider:
vector <Drawable> drawables;
for (size_t i = 0; i < 10000; ++i)
{
Drawable d;
drawables.push_back (d);
}
You will notice potentially many destructor calls when you run this code. When you push_back, a copy is potentially made and the original (d here) is destroyed. Also, when the vector reaches capacity it has to reallocate, which results in every item being copied again, and the originals destroyed.
Objects can also be destroyed at suprising time in the face of temporaries and unexpected copies. Consider:
void DoSomething (Drawable d)
{
}
int main()
{
Drawable d;
for (size_t i = 0; i < 1000; ++i)
{
DoSomething (d);
}
}
This is a naive example because the compiler will likely elide the temporaries in this case. But since DoSomething() takes a Drawable by-value a copy of the original could be made. Depending on other code, the compiler might not even be able to elide this copy.