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 3 years ago.
Improve this question
I need to write a destructor to deallocate the char array, but I always get this error message "pointer being freed was not allocated". It looks like I delete the location more than once, so I try to check if the char pointer is NULL, but it still doesn't work. Please help.
Note that: house object is a member data of another class.
class House {
private:
char * location;
public:
House();
~House();
House::House() {
location = NULL
}
int House::create_house(char init_location[100]) {
location = new char [strlen(init_location) + 1];
strcpy(location, init_location);
return 1;
}
House::~House() {
if (location) {
delete [] location;
location = NULL;
}
}
Edit: I added the constructor and the function showing how my location is allocated.
pointer being freed was not allocated
In the code you show indeed you do not allocate anything. location is just a pointer, there is nothing that could be deleted. You shall only call delete on a pointer to an instance that was acllocated via new.
Use a std::string instead, forget about new and delete and spend your time on the important things.
...
The question has been edited in the meanwhile. The posted code is still missing pieces that would be required to reproduce the error, and as I am unsure what exactly is left out too the only thing to add is that you are most likely violating the rule of 0/3/5. The reason mentioned above for the error is still the same: You are trying to delete something where there is nothing (or something that has already been deleted). And my suggestion is still the same: use std::string.
Related
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 18 days ago.
Improve this question
structure struct_ppl{
char* name;
int age;
}people;
void incription(struct_ppl* ppl)
{
ppl->name = new char[10];
...//some codes, but we do not delete ppl->name
}
int main()
{
people new_ppl;
inscription(&new_ppl);
... //some codes
1. delete(&new_ppl.name);
2. delete(new_ppl.name);
}
In the code above, which one is correct to delete the pointer, 1. or 2.? or neither of them?
thanks for advance
Use std::string and member functions
#include <string>
#include <vector>
#include <iostream>
struct person_t // your struct only holds data for ONE person so ...
{
std::string name;
int age;
~person_t()
{
// no need free memory explicitly, std::string's destructor will do that.
}
//make functions that act on data of a struct a member function
void inscription()
{
name = "?";
}
};
int main()
{
person_t person;
person.inscription();
std::cout << person.name;
return 0;
}
which one is correct to delete the pointer, 1. or 2.? or neither of
them?
Neither, you should and must use delete[] when allocating from new[].
Be aware that the code has a potential for memory leak, calling void incription(struct_ppl* ppl) would leak char* name when called more than once without "deallocating" and destroying the previously allocated char* name.
which one is correct to delete the pointer, 1. or 2.? or neither of them?
Neither of them since you're using the new[] form to allocate the memory dynamically, you must use the corresponding deallocation function of the form delete[].
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have the following code, in which I dynamically allocate memory, and then it deletes it two times in the destructor, causing an error. How can I go about fixing this?
(Nothing wrong, see edit below).
class Song {
private:
char *name;
public:
Song (char *name = "") {
this->name = new char[strlen(name)+1];
this->name[strlen(name)] = '\0';
strcpy(this->name, name);
}
~Song() {
cout << "DEST" << endl; // gets called 2 times, causing an error.
delete [] this->name;
}
};
class CD {
private:
Song songs[1];
public:
CD() {}
~CD() {}
};
int main() {
CD cd1;
Song song1("Song1");
return 0;
}
Edit:
It seems like this code doesn't actually have anything wrong.
The problem was in another part of my code: I used the = operator, but didn't have a copy assignment constructor. Thanks for your help suggesting the rule of three.
It doesn't delete your char array two times, it creates two instancies of your class, so it allocates memory for two strings, then it deletes this memory at destructor. There isn't any double free in your code, what could be the source of your problem (but shouldn't crash your program) is that you assign a string litteral to a char* which is deprecated in c++, you should instead use a const char* in the prototype of your constructor
Song (const char * name);
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 5 years ago.
Improve this question
I have a class like this:
class Foo{
public:
Foo* next = nullptr;
Foo() = default;
Foo(Foo *next){
Foo::next = new Foo(*next);
}
Foo(const Foo ©){
next = new Foo(*copy.next);
}
~Foo(){
delete next;
}
}
It compiles, but when I instantiate the class anywhere, the program crashes. When using a debugger a "breakpoint trap" is triggerd at delete next.
Why is that?
Edit:
The problem was, that there were instances where next could be set to pointers created outside of the class. I assumed you could delete pointers created anywhere.
Your pointer next is uninitialized, pointing to something unknown. delete will (most likely, if you are lucky) throw trying to delete it. Make sure the pointer points to memory allocated with new or is a nullptr.
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());
}
I am trying to define a class in the global scope which contains some dynamically-allocated arrays. When the class' constructor is called, the program does not have access to user-defined parameters read through a parameter file (i.e. the number of years in a simulation) thus it cannot allocate memory to the proper size. My idea was to allocate memory within a private function in the class, and then deallocate it using the destructor. Some example code:
class Simulation{
private:
int initial_call; //a flag used to initialize memory
double *TransferTracker;
public:
Simulation();
~Simulation();
void calc();
};
Simulation simulator; //global instance of Simulation
Simulation::Simulation()
{
initial_call = 1;
}
Simulation::~Simulation()
{
//when calling the destructor, though, the address is
//0xcccccccc and the following attempt to delete produces
//the compiler error.
delete [] TransferTracker; //see error
}
void Simulation::calc()
{
for (int i = 0; i < num_its; i++)
{
if (initial_call)
{
TransferTracker = new double [5];
//The address assigned is, for example, 0x004ce3e0
initial_call = 0;
}
}
//even if this calc function is called multiple times, I see
//that the address is still 0x004ce3e0.
}
The error I receive from the above code fragment is:
Unhandled exception at 0x5d4e57aa (msvcr100d.dll) in LRGV_SAMPLER.exe: 0xC0000005: Access
violation reading location 0xccccccc0.
This error makes sense because I checked the memory address of TransferTracker when entering the destructor. My question is, why do we lose the address when entering the destructor? It probably has something to do with the fact that simulator is global; this paradigm seems to work fine if the class was not global. I am new to object-oriented programming so any help is appreciated!
EDIT: This was basically a blunder on my part and was helped by the answers. Two problems occurred: (1) the pointers were never set to NULL, thus creating confusion on trying to delete unallocated pointers. (2) There were actually two instances of the class in my scope, which was a mistake on my part. In the final code, there will only ever be one instance. Thanks everyone!
Initialize the pointer to NULL (0)
Simulation::Simulation() : TransferTracker(NULL)
{
initial_call = 1;
}
Simulation::~Simulation()
{
//when calling the destructor, though, the address is
//0xcccccccc and the following attempt to delete produces
//the compiler error.
if(TransferTracker) delete [] TransferTracker; //see error
TransferTracker = NULL;
}
That way you can check wether or not it has been initialised when you want to delete it. It's best practice, so do it always, not only at construction
EDIT:
void Simulation::calc()
{
for (int i = 0; i < num_its; i++)
{
if (initial_call)
{
if(TransferTracker) delete [] TransferTracker;
TransferTracker = new double [5];
initial_call = 0;
}
}
}
You have to initialize the value of the instance variable TransferTracker to 0 in the constructor. The problem you're having is the destruction of the Simulation class without actually having assigned dynamic memory to TransferTracker.
Calling delete[] in the destructor with a null pointer is safe. The problem is that if you don't give a value to TransferTracker, it may have any undefined value, that will cause trouble trying to deallocate with delete[].
EDIT:
As per your edit, how do you assure that there is only one instance of the Simulation class? This has to do with if you include several .o files in your build, etc.
I suspect the cause is that your destructor is getting called when you haven't invoked the calc() function, therefore the memory hasn't been allocated yet.
You want to put in place a "guard" that will make sure that you've already allocated the memory before attempting to deallocate the memory for TransferTracker.