I have tried to read lots of solutions to memory leaks occur in copy constructor, but i still didnt understans how to solve it.
For example i have a "Person" class that has those mambers and functions (header files):
#include "Object.h"
#include <string.h>
#include <iostream>
using namespace std;
class Person: public Object
{
private:
char * p_name;
int length;
public:
virtual Object * copy() const;
virtual void print(ostream & os) const;
Person(char * name);
Person(const Person & per);
~Person();
};
In this program Im trying to enter "Objects" to a Vector while Person and Vector inherit from Object.
In both of the copy const i have memory leak problems (the program is working excellent).
For example in this code im getting a memory leaks of all of those 5 char arrays. I have more problems also in Vector memory leaks, but lets start in this simple code in the main (that occurs 5 memory leaks of the char array):
int main ()
{
const int SIZE = 5;
Person* persons[SIZE];
int i;
// preparation of name array
for (i = 0; i<SIZE; i++) {
char* tmp = new char[10];
sprintf(tmp, "P-%d", i);
persons[i] = new Person(tmp);
}
for (i = 0; i < SIZE; i++)
delete persons[i];
return 0;
}
Person class is:
#include "Person.h"
using namespace std;
Object * Person::copy() const
{
Person * p = new Person(*this);
return p;
}
void Person::print(ostream & os) const
{
for (int i = 0; i < this->length-1; i++)
{
os << this->p_name[i];
}
}
Person::Person(char * name)
{
delete this->p_name;
this->length = strlen(name)+1;
p_name = new char[length];
strncpy(p_name, name, length);
}
Person::Person(const Person & per)
{
delete[] this->p_name;
this->length = strlen(per.p_name) + 1;
this->p_name = new char[this->length];
strncpy(this->p_name, per.p_name, this->length);
}
Person::~Person()
{
delete[] this->p_name;
}
I would be thankful for your help!!
In main(), the tmp char array is not deleted, and that's the first memory leakage I'm seeing.
In the Person(char * name) constructor you call a delete on
Person::Person(char * name)
{
delete this->p_name;
the p_name is not allocated, so the behavior is undefined. And p_name is an array, so delete[] should be used.
if you use the std::string class, you can at least avoid the confusion between delete and delete[]
You don't have just a memory leak. You have a full-fledged, memory-corrupting, undefined behavior:
Person::Person(char * name)
{
delete this->p_name;
This is your constructor. The p_name class member does not appear to be initialized in any way. And the first thing you do, is you try to delete it.
So, whatever random value p_name will contain, as a result of the most recent set of cosmic rays striking the RAM capacitors that hold its initial value, the first thing the constructor does is try to free the pointed-to memory.
Before you can worry about any alleged leaks from your copy constructor, you need to fix a bunch of problems, like this, elsewhere.
in main(), where you prepare your c you allocate 5 char buffers, that're never freed
also (not speaking of std::string which would help you with your string stuff) , get rid of the unneeded "this->"s:
Person::Person(const Person & per)
{
delete[] this->p_name;
this->length = strlen(per.p_name) + 1;
this->p_name = new char[this->length];
strncpy(this->p_name, per.p_name, this->length);
}
could look like this:
Person::Person(const Person & per)
{
delete[] p_name;
length = strlen(per.p_name) + 1;
p_name = new char[length];
strncpy(p_name, per.p_name, length);
}
There are some problems with delete.
In your main, in the first while you have to delete temp; in the second well just don't use it, use delete [] persons.
In your copy constructor don't use delete this->p_name, that's not correct.
At first you have to set the pointer to null so p_name=NULL, and then use setters and getters, same for your value constructor.
And in your destructor, test if p_name exists before deleting it.
Related
I'm new to C++ and try to understand how to create and use a class in C++.
For this I have the following code:
class MyClass
{
public:
MyClass()
{
_num = 0;
_name = "";
}
MyClass(MyClass* pMyClass)
{
_num = pMyClass->_num;
_name = pMyClass->_name;
}
void PrintValues() { std::cout << _name << ":" << _num << std::endl; }
void SetValues(int number, std::string name)
{
_num = number;
_name = name;
}
private:
int _num;
std::string _name;
};
int main()
{
std::vector<MyClass*> myClassArray;
MyClass myLocalObject = new MyClass();
for (int i = 0; i < 3; i++)
{
myLocalObject.SetValues(i, "test");
myClassArray.push_back(new MyClass(myLocalObject));
}
myClassArray[1]->PrintValues();
// use myClassArray further
}
I get a similar example from the internet and try to understand it.
My intentions is to populate myClassArray with new class objects.
If I compile the code above using VisualStudio 2022 I get no errors, but I'm not sure it doesn't produce memory leaks or if there is a faster and simple approach.
Especially I do not understand the following line:
MyClass myLocalObject = new MyClass();
myLocalObject is created on the stack but is initialized with a heap value (because of the new). If new operator is used where should delete must apply?
Thank you for any suggestions!
You have a memory leak at MyClass myLocalObject = new MyClass();, since the dynamically-allocated object is used to converting-construct the new myLocalObject (this was almost but not quite a copy constructor) and then the pointer is lost.
You also didn't show the code using the vector, but if it doesn't delete the pointers inside, you will have more memory leaks.
There's no reason to have an almost-copy-constructor; the compiler has provided you with a better real copy-constructor.
The faster and simpler approach is to recognize that this code doesn't need pointers at all.
class MyClass
{
public:
MyClass()
: _num(), _name() // initialize is better than assignment
{
//_num = 0;
//_name = "";
}
// compiler provides a copy constructor taking const MyClass&
//MyClass(MyClass* pMyClass)
//{
// _num = pMyClass->_num;
// _name = pMyClass->_name;
//}
void PrintValues() { std::cout << _name << ":" << _num << std::endl; }
void SetValues(int number, std::string name)
{
_num = number;
_name = name;
}
private:
int _num;
std::string _name;
};
int main()
{
std::vector<MyClass> myClassArray; // not a pointer
MyClass myLocalObject; // = new MyClass(); // why copy a default instance when you can just default initialize?
for (int i = 0; i < 3; i++)
{
myLocalObject.SetValues(i, "test"); // works just as before
myClassArray.push_back(/*new MyClass*/(myLocalObject)); // don't need a pointer, vector knows how to copy objects
// also, this was using the "real" copy-constructor, not the conversion from pointer
}
myClassArray[1].PrintValues(); // instead of ->
// use myClassArray further
}
for cases where a pointer is necessary, for example polymorphism, use a smart pointer:
std::vector<std::unique_ptr<MyClass>> myClassArray; // smart pointer
myClassArray.push_back(make_unique<MyDerivedClass>(stuff));
std::unique_ptr will automatically free the object when it is removed from the vector (unless you explicitly move it out), avoiding the need to remember to delete.
There are basically 2 ways to instantiate objects of classes.
Dynamic allocation (on heap)
MyClass* myLocalObject = new MyClass(); // dynamically allocates memory and assigns memory address to myLocalObject
Example for your loop:
class MyClass
{
private:
int _num;
std::string _name;
public:
// let's add an additional constuctor having default values
// that makes it easier later on
// if parameters are passed, they are used, or the defalt values, if not
// can call it like MyClass(), MyClass(123), or MyClass(456,"hello")
// you might want to pass larger data as reference, to avoid copying it
MyClass(int num=0, std::string name = "some default text")
: _num(num), _name(name)
{}
};
std::vector<MyClass*> myClassArray; // your array of pointers
for (int i = 0; i < 3; i++)
myClassArray.push_back(new MyClass(i, "test"));
// delete
for (auto& pointerToElement : myClassArray) // get a reference to each element (which is a pointer)
delete pointerToElement; // delete element (call's destructor if defined)
In that case you must delete myLocalObject; or you get a memory leak.
Instead of dealing with raw pointers, especially when new to C++, I recommend to use smart pointers, that deal with memory management for you.
Automatic allocation (on stack when possible)
MyClass myLocalObject = MyClass(); // automatically allocates memory and creates myLocalObject
This happens usually on stack (if possible). That's much faster and you don't have to deal with dynamic memory management
Example for your loop:
std::vector<MyClass> myClassArray; // now "containg" the memory of objects itself
for (int i = 0; i < 3; i++)
{
myClassArray.emplace_back(i, "test"); // we use emplace_back instead to construct instances of type MyClass directly into the array
}
// no deletion required here
// destructors of each element will be called (if defined) when myClassArray is deleted automatically when out of scope
There are other ways, like dynamic stack allocation and other black magic, but recommend to focus on "the standard".
In case of dealing with large amounts of data, you might want to use std::vector::reserve. In combination with automatic/stack allocation that helps to speed up a lot by limiting memory allocations to 1 at all instead of 1 per element.
Hope that helps :-)
I'm trying out a C# style string implementation in C++.
I have created an object and a pointer for class String, and assigned the object to the pointer. When i try to modify the object via the pointer instead of modifying the existing object i want to create a new object and make the pointer point it.
So i have overloaded the "=" operator, and creating a new object in the operator overloaded method. In order to reflect the change i need to use ss=*ss = "name";
Any suggestion to improve this code.
Below is my sample code
class String
{
char *str;
public:
String(char* str_in)
{
str = new char[strlen(str_in)];
strcpy(str, str_in);
}
String* operator=(char* s)
{
return new String(s);
}
};
int main()
{
String s="sample";
String *ss;
ss = &s;
ss=*ss = "name";
return 0;
}
I also tried to modify the this pointer, but not working as expected
String *ptr;
ptr = const_cast<String*>(this);
ptr = new String(s);
I would recommend some changes like this:
#include <string.h>
class String
{
char *str;
public:
String(const char* str_in)
{
str = new char[strlen(str_in)];
strcpy(str, str_in);
}
~String()
{
delete [] str;
}
String& operator=(const char* s)
{
char* tmp = new char[strlen(s)];
strcpy(tmp, s);
delete [] str;
str = tmp;
return *this;
}
};
int main()
{
String s("sample");
String *ss;
ss = &s;
ss = new String("name");
delete ss;
return 0;
}
First of all, you need an appropriate destructor or you are going to have a memory leak when String gets destroyed. Deleting the char* fixes this (since it is an array, we use the array delete).
Secondly, in C++, we almost always return a reference for operator= (not a pointer). So this revised operator= function is probably better - it deletes the old string, allocates memory for the new string, copies the new string, and returns *this.
Third, you can use const char* instead of char* for the constructor and assignment operator since you are not editing it.
In main(), I also created a new object for the pointer to point to since you requested that in the original post (and then it is deleted afterwards to avoid a memory leak).
Let me know if you have any questions with those changes.
I tried to search same questions, but not one helped me. When I run program I get the "A Buffer Overrun has occurred..." error.
Constr:
Player(char* n)
{
length = strlen(n);
name = new char[length+1];
for(unsigned int i(0); i < length; i++)
name[i] = n[i];
name[length] = '\0';
}
Destr:
~Player(void)
{
delete [] name;
}
I've NULL terminated string and don't get out of bounds, what is problem?
There's no obvious error in the code you've posted, but trying to manage dynamic memory by juggling raw pointers will almost inevitably lead to errors like this.
Perhaps you haven't correctly implemented or deleted the copy constructor and copy-assignment operator, per the Rule of Three. In that case, copying a Player object will give two objects with pointers to the same array; both of them will try to delete that array, giving undefined behaviour.
The simplest solution is to manage your string with a class designed for managing strings. Change the type of name to std::string, and then the constructor can simply be something like
explicit Player(std::string const & n) : name(n) {}
and there's no need to declare a destructor (or move/copy constructor/assignment operators) at all.
So... a solution by using an std::string has been provided, but let me give another solution, keeping your member variables intact.
The problem is this. Suppose you have this code somewhere:
Player p1("Bob"); // Okay
Player p2("Annie"); // Okay
p2 = p1; // Oops! (1)
Player p3(p1); // Oops! (2)
At (1), the method Player& Player::operator=(const Player&) is called. Since you didn't provide one, the compiler generates one for you. When it does, it simply assumes that it may copy over all member variables. In this case, it copies over Player::name and Player::length. So, we have p1.name == p2.name. Now when the destructor of p2 is called, the allocated memory pointed to by p2.name is deleted. Then when the destructor of p1 is called, the same memory will be deleted (since p1.name == p2.name)! That's illegal.
To fix this, you can write an assignment operator yourself.
Player& Player::operator = (const Player& other)
{
// Are we the same object?
if (this == &other) return *this;
// Delete the memory. So call the destructor.
this->~Player();
// Make room for the new name.
length = other.length;
name = new char[length + 1];
// Copy it over.
for (unsigned int i = 0; i < length; ++i) name[i] = other.name[i];
name[length] = '\0';
// All done!
return *this;
}
At (2), the same problem occurs. You do not have a copy constructor, so the compiler generates one for you. It will also assume that it may copy over all the member variables, so when the destructors get called, they'll try to delete the same memory again. To fix this, also write a copy constructor:
Player::Player(const Player& other)
{
if (this == &other) return;
length = other.length;
name = new char[length + 1];
for (unsigned int i = 0; i < length; ++i) name[i] = other.name[i];
}
At the end of the day you should use an std::string though.
I am trying to make a deep copy (for copy on write) of an object but I get a segmentation fault.
I am using a hashtable with linked list.
class Person
{
public:
Person(const char * id,int nb)
{
this->id=strdup(id);
this->nb=nb;
this->init=init;
this->next=NULL;
}
Person(const Person& rhs) :
nb(rhs.nb),
init(rhs.init),
id(strdup(rhs.id)),
next(rhs.next == NULL ? NULL : new Person(*rhs.next)) {}
char* strdup(char const* in)
{
char* ret = new char[strlen(in)+1];
strcpy(ret, in);
return ret;
}
int nb,init;
const char * id;
Person *next;
};
Hashtable deepcopy (const Hashtable& rhs)
{
num[0]=num[0]-1;
Person** array=rhs.table;
Hashtable autre;
for (int i = 0 ; i < size; ++i)
if (autre.table[i]!=NULL)
autre.table[i] = new Person(*array[i]);
return autre;
num[0]=1;
}
the attributs of my class Hashtable:
Person **table;
int* num;
EDIT: this problem seem to be fixed.
What is wrong with my deep copy? I don't understand. I think that my copy constructor is good but I don't understand why I get a seg fault when I run it.
This code must be fixed:
for (int i = 0 ; i < size; ++i)
autre.table[i] = new Person(*array[i]);
table has fixed size, and it's filled with null-pointers. In your loop, you don't check if the element to be copied is a null-pointer, so you derefence it and try to copy the entity which even doesn't exist.
for (int i = 0 ; i < size; ++i) {
if(array[i] != NULL) {
autre.table[i] = new Person(*array[i]);
}
}
PS: It's better to use nullptr instead of NULL.
Problems that I see:
Default constructor of Person.
Person(const char * id,int nb)
{
this->id=id;
this->next=NULL;
}
If I use
Person foo()
{
char id[] = "John";
return Person(id, 0);
}
Person a = foo();
Then the stack memory used for holding "John" in foo is now held on to by a, which will lead to undefined behavior.
You need to take ownership of the input string. Use std::string for id instead of char const*.
Copy constructor of Person.
The statement
id(rhs.id),
will be a problem if you decide to use char const* as type for id. If you switch it to std::string, it won't be a problem.
Copy constructor of HashTable makes a shallow copy of table. This will be a problem if you decide to delete the table in the destructor of HashTable. If you don't delete table in the destructor of HashTable, you have a memory leak.
In deepcopy, you are not checking whether array[i] is NULL before dereferencing it. This has already been pointed out by #alphashooter. Additionally, you are creating a deep copy in a local variable of the function,autre. The deep copy is not visible outside the function unless you return autre from it.
EDIT
Since you are not allowed, to use std::string, you will have to allocate memory for the char const* in the default constructor as well as the copy constructor. If your platform has the non-standard function strdup and you are allowed to use it, you can change the default constructor to:
Person(const char * id,int nb)
{
this->id=strdup(id);
this->next=NULL;
}
You need to make a similar change to the copy constructor.
If you don't have strdup or you are not allowed to use it, you can define it. It's a very simple function to write.
char* strdup(char const* in)
{
char* ret = new char[strlen(in)+1];
strcpy(ret, in);
return ret;
}
noob here. I'm doing an exercise from a book and the compiler reports no errors, but the program crashes when I try to run it.
I'm trying to run a little program exercising the different methods of the Cow class. It explicitly has: a constructor, a default constructor, a copy constructor, a destructor, an overloaded assignment operator, and a method to show its contents.
I'll put the whole project:
Class specification:
//cow.h -- For project Exercise 12.1.cbp
class Cow
{
char name[20]; // memory is allocated in the stack
char *hobby;
double weight;
public:
Cow();
Cow(const char *nm, const char *ho, double wt);
Cow(const Cow &c);
~Cow();
Cow & operator=(const Cow &c);
void ShowCow() const; // display all cow data
};
Methods implementation:
// cow.cpp -- Cow class methods implementation (compile with main.cpp)
#include <cstring>
#include <iostream>
#include "cow.h"
Cow::Cow() // default destructor
{
strcpy(name, "empty");
hobby = new char[6]; // makes it compatible with delete[]
strcpy(hobby, "empty");
weight = 0.0;
}
Cow::Cow(const char *nm, const char *ho, double wt)
{
strcpy(name, nm); // name = nm; is wrong, it copies the address of the argument pointer (swallow copying)
/*if (name[20] != '\0') // if it's not a string, make it a string (in case nm is larger than 20)
name[20] = '\0';*/
hobby = new char[strlen(ho) + 1]; // allocates the needed memory to hold the argument string
strcpy(hobby, ho); // copies the pointed-to data from the argument pointer to the class pointer
weight = wt;
}
Cow::Cow(const Cow &c) // copy constructor
{
strcpy(name, c.name); // copies the value to the desired address
char *temp = hobby; // stores the address of the memory previously allocated with new
hobby = new char[strlen(c.hobby) + 1];
strcpy(hobby, c.hobby); // copies the value to the new address
delete[] temp; // deletes the previously new allocated memory
weight = c.weight;
}
Cow::~Cow()
{
delete[] hobby;
}
Cow & Cow::operator=(const Cow &c) // overloaded assignment operator
{
strcpy(name, c.name);
char *temp = hobby;
hobby = new char[strlen(c.hobby) + 1];
strcpy(hobby, c.hobby);
delete[] temp;
weight = c.weight;
return *this;
}
void Cow::ShowCow() const
{
std::cout << "Name: " << name << '\n';
std::cout << "Hobby: " << hobby << '\n';
std::cout << "Weight: " << weight << "\n\n";
}
Client:
// main.cpp -- Exercising the Cow class (compile with cow.cpp)
#include "cow.h"
#include <iostream>
int main()
{
using std::cout;
using std::cin;
Cow subject1; // default constructor
Cow subject2("Maria", "Reading", 120); // non-default constructor
Cow subject3("Lula", "Cinema", 135);
subject1 = subject3; // overloaded assignment operator
Cow subject4 = subject2; // copy constructor
subject1.ShowCow();
subject2.ShowCow();
subject3.ShowCow();
subject4.ShowCow();
cin.get();
return 0;
}
I was hiding some parts of the code to locate the possible problem and it seems the progam doesn't like this two lines:
subject1 = subject3;
Cow subject4 = subject2
And in particular, in the overloaded assignment operator and the copy constructor, if I hide the delete[] temp line, the program doesn't crash.
I'm total noob and probably is something stupid but I can't see what I'm doing wrong in these definitions.
Any help?
Cow::Cow(const Cow &c) // copy constructor
{
strcpy(name, c.name); // copies the value to the desired address
char *temp = hobby; // stores the address of the memory previously allocated with new
hobby = new char[strlen(c.hobby) + 1];
strcpy(hobby, c.hobby); // copies the value to the new address
delete[] temp; // deletes the previously new allocated memory
weight = c.weight;
}
It's the copy c-tor. There is no previously allocated members. this->hobby points to random garbage. So when you delete[] temp (i.e. this->hobby before the new assignment), you get UB.
Cow & Cow::operator=(const Cow &c) // overloaded assignment operator
{
strcpy(name, c.name);
char *temp = hobby;
hobby = new char[strlen(c.hobby) + 1];
strcpy(hobby, c.hobby);
delete[] temp;
hobby = name;
weight = c.weight;
return *this;
}
hobby = name is incorrect, as it causes a memory leak + destructor will try to delete an object that was not allocated with operator new[].
#ForEveR Already noted that your copy constructor is deleting memory that was never allocated.
But I'm going to argue that the entire exercise is flawed and is teaching C with classes, NOT C++. If you used string all your problems would go away because you wouldn't have to manage resources directly. This eliminates the need for you to write a destructor or copy assignment/constructor entirely. For example:
class Cow
{
std::string name;
std::string hobby;
double weight;
public:
Cow();
Cow(const std::string& nm, const std::string& ho, double wt);
void ShowCow() const; // display all cow data
};