Here is the program...
class CopyCon
{
public:
char *name;
CopyCon()
{
name = new char;
}
CopyCon(const CopyCon &objCopyCon)
{
name = new char;
_tcscpy(name,objCopyCon.name);
}
~CopyCon()
{
if( name != NULL )
{
delete name;
name = NULL;
}
}
};
int main()
{
CopyCon objCopyCon1;
objCopyCon1.name = "Hai";
CopyCon objCopyCon2(objCopyCon1);
objCopyCon1.name = "Hello";
cout<<objCopyCon2.name<<endl;
return 0;
}
Once the code execution completes, when the destructor called, it crashes on 'delete' saying...
Debug Error!
Program: ...
HEAP CORRUPTION DETECTED: after Normal block (#124) at 0x00366990.
CRT detected that the application wrote to memory after end of heap buffer.
(Press Retry to debug the application)
Don't we have to clear the heap memory in destructor. What's wrong with this program? Pls someone help!
Copy constructor works perfectly as intended. But still... !?
The problem is you are allocating only one char in the copy constructor.
In main you are assigning a 4-byte string (remember the null), but when you copy the object, you only allocate enough room for 1 byte.
What you probably want to do is change
name = new char;
to
name = new char[tcslen(objCopyCon.name) + 1];
And in the destructor:
delete name;
to
delete [] name;
Also:
You are assigning "Hai" and "Hello" to objCopyCon1.name which is hiding the memory allocated in the constructor. This memory can never be freed!
You write past the allocated variable and that is undefined behavior.
When the folloing lines run
CopyCon objCopyCon1;
objCopyCon1.name = "Hai";
CopyCon objCopyCon2(objCopyCon1);
_tcscpy() copies 4 characters (3 letters and the null terminator) into a buffer that can legally hold only one character. So you write past the buffer end and this leads to heap corruption.
You need to alocate the buffer of the right size:
CopyCon(const CopyCon &objCopyCon)
{
name = new char[_tcslen(objCopyCon.name) +1];
_tcscpy(name,objCopyCon.name);
}
also you need to change the delete in the destructor to delete[] and also change all other new calls to new[] to avoid undefined behavior.
You are allocating one character and trying copy multiple characters into that memory location. First find out the length of the string then allocate length + 1 characters (extra char to accommodate the NULL character) using new char[length+1] syntax. You need to correspondingly change your destructor to delete[] name.
Besides the new char issue that everyone mentioned, the strings "Hai" and "Hello" reside in read-only memory. This means you cannot delete them (but you do so in your destructor) - this does generate crashes. Your code should not assign to name directly, but use a set function such as:
void set_name(const char *new_name)
{
delete [] name; // delete is a no-op on a NULL pointer
name = new char[tcslen(new_name) + 1];
_tcscpy(name,new_name);
}
I'm surprised that assignment does not produce a compiler warning to be honest. You are assigning a const char * to a char *, which can lead to all sorts of problems like the one you're seeing.
The job of the copy ctor should be to create a copy of the object. So the char array pointed to by name in the both the objects should be of the same size and same content, which is not happening in your case. So change
name = new char; // allocates only one char
to
name = new char[strlen(objCopyCon.name) + 1]; // allocate array of char
You need to allocate enough memory to hold the information you are trying to store. "Hai" is 4 bytes or chars (including the null terminator) and you have only allocated one. You also do not copy strings from one memory location to another using "=". You need to strncpy the string across.
Use std::string it will make your life a million times easier :)
Here the code that works perfect!
class CopyCon
{
public:
char *name;
CopyCon()
{
name = NULL;
}
CopyCon(const CopyCon &objCopyCon)
{
name = new char[_tcslen(objCopyCon.name)+1];
_tcscpy(name,objCopyCon.name);
}
~CopyCon()
{
if( name != NULL )
{
delete[] name;
name = NULL;
}
}
void set_name(const char *new_name)
{
//delete [] name; // delete is a no-op on a NULL pointer
if( NULL != name)
{
delete[] name; name = NULL;
}
name = new char[_tcslen(new_name) + 1];
_tcscpy(name,new_name);
}
};
int main()
{
CopyCon objCopyCon1;
objCopyCon1.set_name("Hai");
CopyCon objCopyCon2(objCopyCon1);
objCopyCon1.set_name("Hello");
cout<<objCopyCon1.name<<endl;
cout<<objCopyCon2.name<<endl;
return 0;
}
Thanks to all for their view points. It really helped!
Related
I am implementing a stack and I would like to push and pop string data. can I not just set
string name = originalString ???
here is what I have for push:
void push(StackNode** top_ref, int nAttack, int nDefense, string nName, string nType) {
StackNode* stackNode = (StackNode*)malloc(sizeof(StackNode));
stackNode->attack = nAttack;
stackNode->defense = nDefense;
stackNode->name = nName; //not working
stackNode->type = nType; //not working
stackNode->next = NULL;
stackNode->next = *top_ref;
*top_ref = stackNode;
}
where stackNode->name
and stackNode->type is already defind as a string
I keep getting: "Error reading characters of string."
The issue is malloc doesn't play well with objects. See Does malloc create a new instance of the class or not?
malloc allocates enough space to hold a StackNode, but doesn't call the constructor on it. Nor does it create the underlying member objects, your strings included. To do so, you need to do like described in this answer:
A* a = (A*)malloc(sizeof(A));
new (a) A();
a->~A();
free(a);
But at this point, you really should just be using new anyway. There's very little reason to use new in C++ (there's a time and a place, but minimize it). There's even fewer times when it's right to call malloc.
Do
StackNode* stackNode = new StackNode;
which will call the constructor appropriately. Remember to call delete on the memory when you're done with it!
Whenever a the String Destructor is hit it Triggers a Breakpoint, i think i might be deleting the same variable twice or not assigning the right amount of memory during the manipulation of m_str
#include "String.h"
#include <iostream>
using namespace std;
String::String()
{
m_str = nullptr;
}
String::String(const char* newStr)
{
m_str = new char[strlen(newStr)+ 1];
strcpy(m_str, newStr);
}
String::~String()
{
if (m_str != nullptr)
{
delete[] m_str;
}
}
void String::operator=(const String & myString)
{
if (m_str != nullptr)
{
delete[] m_str; //Breakpoint Apears Here
};
m_str = new char[strlen(myString.m_str) + 1];
m_str = myString.m_str;
}
void String::operator=(char* newStr)
{
if (m_str != nullptr)
{
delete[] m_str;
};
m_str = new char[strlen(newStr) + 1];
m_str = newStr;
}
}
Assigning one const char * to another as you do e.g. In the assignment operators doesn't copy the string, it just copies the pointer. So instead of two separate strings, you now have two pointers, pointing to the same string.
So for one, you are leaking the newly created char array and second, you are trying to delete whatever has been passed to the assignment operator, which in your case is probably a string literal instead of something that was created via new. Also in the case of the copy assignment operator, you would end up with two String objects pointing to the same char array and thus double deletion.
To solve this Problem, just use strcpy as you did in the constructor.
You correctly use a strcpy to copy chars from original char array in String::String(const char* newStr), but in all other places in your code, you wrongly write:
m_str = new char[strlen(myString.m_str) + 1];
m_str = myString.m_str;
First line correctly allocates an array of correct size, but the second erases the pointer obtained by new so:
you get a memory leak, since the allocated memory has no pointer on it any longer and will never be freed
the m_str member points to the original char array. If it is later deleted you have a dangling pointer, and if you delete this instance first, you will try to delete the original char pointer in another instance making it dangling, or even try to delete a static or local array.
TL/DR: consistently copy the character array with strcpy (or std::copy)
Please refer below program before answering question. Explained the code in comments.
So my question here is in assignment operator overloading how to handle the case where new() failed to allocate memory.
For example Obj1 is holding string "GeeksQuiz". Assigning Obj2 to Obj1. During assigning (in assignment operator overload function) first we free Obj1 and then recreate Obj1 with Obj2 values. So in the case where new fails to allocate memory how to retain old Obj1 values? Since we freed Obj1 values in starting of function.
All that I want is to have the old values for Obj1 when the assigning operation fails.
Please help me in this. I want perfect code, without any memory leaks covering all scenarios. Thanks in Advance
#include<iostream>
#include<cstring>
using namespace std;
class String
{
private:
char *string_data;
int size;
public:
String(const char *str = NULL); // constructor
~String() { delete [] string_data; }// destructor
void print() { cout << string_data << endl; } // Function to print string
String& operator = (const String &); // assignment operator overload
};
String::String(const char *str) // Constructor
{
size = strlen(str);
string_data = new char[size+1];
if (string_data != NULL)
strcpy(string_data, str);
else
cout<<"compiler failed to allocate new memory";
}
String& String::operator = (const String &str) // assignment operator overload
{
if(this != &str)
{
delete [] string_data; // Deleting old data and assigning new data below
size = str.size;
string_data = new char[size+1];
if(string_data != NULL) // This condition is for cheking new memory is success
strcpy(string_data, str.string_data);
else
cout<<"compiler failed to allocate new memory"; // My quetsion comes in this scenario...
}
return *this;
}
int main()
{
String Obj1("GeeksQuiz");
String Obj2("stackoverflow");
Obj1.print(); // Printing Before assigment
Obj2.print();
Obj1 = Obj2; // Assignment is done.
Obj1.print(); // Printing After assigment
Obj2.print();
return 0;
}
First of all, implementing a robust string is difficult, unless you want to do it for learning purposes always use std::string.
Then take into account that operator new always returns non-null pointers (unless you are also implementing a non standard custom new operator), instead it throws a std::bad_alloc exception if it fails to allocate the data. If you want to handle the allocation fail case you need to add a try-catch block
char *data = NULL;
try {
data = new char[str.size + 1];
} catch (std::bad_alloc &e) {
std::cout << "Allocation failed: " << e.what() << std::endl;
throw; // <- You probably want to rethrow the exception.
}
strcpy(data, str.string_data);
delete [] string_data;
string_data = data;
size = str.size;
The important part is to leave your class in a consistent state when the exception is thrown, that's why you must first allocate the new data and then if it succeeds, delete the old data. However bad_alloc exceptions are rarely handled at class level, commonly you let the exception be thrown (that's why I rethrow in the code sample) and let the client code handle that.
If you really want your code to be exception proof I would advice the use of smart pointers, and as already said, in this case use std::string.
Temporary or dummy variables.
Allocate new memory, assign pointer to a temporary variable. If it succeeds then free the old memory and reassign that pointer variable.
Pseudo-ish code:
char *temp = new char[new_size];
std::copy(new_data, new_data + new_size, temp);
delete [] old_data;
old_data = temp;
old_size = new_size;
1st allocate memory in a temporary variable, if it's successful then only delete old value.
As someone who never dealt with freeing memory and so on, I got the task to create a dynamic array of struct and create functions to add or delete array elements. When deleting I have to free the memory which is no longer necessary.
when deleting the 2nd element of an array of the size of 3, I move the 3rd element to the 2nd position and then delete the last one. When deleting the last one, I always get an error... Is there anyone who can find an solution for me?
struct myFriend {
myFriend() {
number=0;
hobbys = new char*[10];
}
int number;
char* name;
char** hobbys;
};
int main() {
myFriend* friendList = new myFriend[10];
myFriend* tempFriend = new myFriend;
tempFriend->number=1;
tempFriend->name = "ABC";
myFriend* tempFriend2 = new myFriend;
tempFriend2->number=2;
tempFriend->name = "XYZ";
myFriend* tempFriend3 = new myFriend;
tempFriend3->number=3;
tempFriend3->name = "123";
friendList[0] = *tempFriend;
friendList[1] = *tempFriend2;
friendList[2] = *tempFriend3;
friendList[1] = friendList[2]; //move 3rd element on 2nd position
delete &(friendList[2]); //and delete 3rd element to free memory
}
Why did you create temporary variables? They're not even needed.
If you use std::vector and std::string, the problem you're facing will disappear automatically:
std::vector<myFriend> friendList(10);
friendList[0]->number=1;
friendList[0]->name = "ABC";
friendList[1]->number=2;
friendList[1]->name = "XYZ";
friendList[2]->number=3;
friendList[2]->name = "123";
To make it work, you should redefine your struct as:
struct myFriend {
int number;
std::string name;
std::vector<std::string> hobbys;
};
If you're asked to work with raw pointers, then you should be doing something like this:
struct Friend
{
int number;
char* name;
};
Friend * friends = new Friend[3];
friends[0]->number=1;
friends[0]->name = new char[4];
strcpy(friends[0]->name, "ABC");
//similarly for other : friends[1] and friends[2]
//this is how you should be deleting the allocated memory.
delete [] friends[0]->name;
delete [] friends[1]->name;
delete [] friends[2]->name;
delete [] friends; //and finally this!
And if you do any of the following, it would be wrong, and would invoke undefined behavior:
delete friends[2]; //wrong
delete &(friends[2]); //wrong
It is impossible to delete a subset from array allocated by new []
myFriend* friendList = new myFriend[10];
You have a single whole array
+------------------------------------------------------------------+
| friendList[0] | friendList[1] | ..... | friendList[9] |
+------------------------------------------------------------------+
You can not delete &(friendList[2]).
You get from C++ whole array of 10 elements.
This array starts from friendList (or &(friendList[0])).
operator delete with pointer to the address returned by new (i.e. friendList) is valid
only.
Two things I noticed. (1) You are apparently supposed to "create functions to add or delete elements" but you haven't done that, you have only created one function. (2) You are making your work harder than it needs to be by using a struct that also needs to manage memory. I suggest you use a simpler struct.
Your assignment is, in effect, to make a simple 'vector' class, so I suggest that you do that. Start with a struct that is empty. If the teacher requires you to use the myFriend struct as written, you can add that in after you finish making your vector like functions. I'm going to assume that you aren't allowed to make a class yet because most instructors make the mistake of leaving that until last.
struct MyStruct {
int value; // start with just one value here. Dealing with pointers is more advanced.
};
MyStruct* array;
int size;
int capacity;
void addMyStruct(MyStruct& value); // adds a MyStruct object to the end.
void removeMyStructAtPosition(int position); // removes the MyStruct object that is at 'position'
// I leave the functions for you to implement, it's your homework after all, but I give some clues below.
void addMyStruct(MyStruct& value) {
// First check that there is enough capacity in your array to hold the new value.
// If not, then make a bigger array, and copy all the contents of the old array to the new one.
// (The first time through, you will also have to create the array.)
// Next assign the new value to array[size]; and increment size
}
void removeMyStructAtPosition(int position) {
// If the position is at end (size - 1,) then simply decrement size.
// Otherwise you have to push all the structs one to the left (array[i] = array[i + 1])
// from position to the end of the array.
}
int main() {
// test your new class here.
// don't forget to delete or delete [] any memory that you newed.
}
The array size is fixed at 10, so you don't need to delete any elements from it. But you do need to delete the name and hobbys elements of friendList[1] (and before you overwrite it). There are two problems here:
You are setting friendList[0]->name = "ABC"; Here, "ABC" is a constant zero-terminated string somewhere in memory. You are not allowed to delete it. So you have to make a copy.
You want to delete hobby[i] whenever it was assigned. But in your code, you can't tell whether it was assigned. So you have to set every element to 0 in the constructor, so that you will later know which elements to delete.
The proper place to delete these elements is in myFriends's destructor.
It seems the point of the question is to manage a dynamic array. The main problem is that he is using an array of friendList. Use an array of pointers to friendList:
struct myFriend {
myFriend() {
number=0;
hobbys = new char*[10];
}
int number;
char* name;
char** hobbys;
};
int main() {
myFriend** friendList = new myFriend*[10];
myFriend* tempFriend = new myFriend;
tempFriend->number=1;
tempFriend->name = "ABC";
myFriend* tempFriend2 = new myFriend;
tempFriend2->number=2;
tempFriend->name = "XYZ";
myFriend* tempFriend3 = new myFriend;
tempFriend3->number=3;
tempFriend3->name = "123";
friendList[0] = tempFriend;
friendList[1] = tempFriend2;
friendList[2] = tempFriend3;
friendList[1] = friendList[2]; //move 3rd element on 2nd position
delete friendList[2]; //and delete 3rd element to free memory
}
But everybody else is right -- there are major issues around memory allocation for both 'hobbys' and for 'name' that you need to sort out separately.
To do your homework I'd suggest to learn much more about pointers, new/delete operators, new[]/delete[] operators (not to be confused with new/delete operators) and objects creation/copying/constructors/destructors. It is basic C++ features and your task is all about this.
To point some directions:
1) When you dynamically allocate the object like this
MyType* p = new MyType;
or
MyType* p = new MyType(constructor_parameters);
you get the pointer p to the created object (new allocates memory for a single object of type MyType and calls the constructor of that object).
After your work with that object is finished you have to call
delete p;
delete calls the destructor of the object and then frees memory. If you don't call delete your memory is leaked. If you call it more than once the behavior is undefined (likely heap corruption that may lead to program crash - sometimes at very strange moment).
2) When you dynamically allocate array like this
MyType* p = new MyType[n];
you get the pointer p to the array of n created object located sequentially in memory (new[] allocates single block of memory for n objects of type MyType and calls default constructors for every object).
You cannot change the number of elements in this dynamic array. You can only delete it.
After your work with that array is finished you have to call
delete[] p; // not "delete p;"
delete[] calls the destructor of every object in the array and then frees memory. If you don't call delete[] your memory is leaked. If you call it more than once the behavior is undefined (likely program crash). If you call delete instead of delete[] the behavior is undefined (likely destructor called only for the first object and then attempt to free memory block - but could be anything).
3) When you assign the struct/class then operator= is called. If you have no operator= explicitly defined for your struct/class then implicit operator= is generated (it performs assignment of every non-static member of your struct/class).
Please have a glance at this program:
class CopyCon
{
public:
char *name;
CopyCon()
{
name = new char[20];
name = "Hai";//_tcscpy(name,"Hai");
}
CopyCon(const CopyCon &objCopyCon)
{
name = new char[_tcslen(objCopyCon.name)+1];
_tcscpy(name,objCopyCon.name);
}
~CopyCon()
{
if( name != NULL )
{
delete[] name;
name = NULL;
}
}
};
int main()
{
CopyCon obj1;
CopyCon obj2(obj1);
cout<<obj1.name<<endl;
cout<<obj2.name<<endl;
}
This program crashes on execution. Error: "Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)"
If I assign "Hai" to name using aasignment operator, its crashing. Where as when I use string func _tcscpy to assign "Hai" to name, its working perfectly. Can some one explain why so?
name = "Hai";//_tcscpy(name,"Hai");
You are not copying contents of "Hai" into name instead name will point to a read only memory ( whose contents are "Hai")
if you try to delete name later then it might crash.
In the default constructor
CopyCon()
{
name = new char[20];
name = "Hai";//_tcscpy(name,"Hai");
}
you assign the address of a string literal to the pointer and in the destructor you call delete[] on it, that's undefined behavior. delete[] should only be called on addresses returned by new[].
When you instead use _tcscpy() you copy the literal content to the buffer allocated by new[] and then the destructor runs fine.
When you use assignment, you make the pointer name point at the string literal "Hai". This later gets deleted in the destructor. However, the string literal was not allocated with new, and cannot be deleted like this, so you get undefined behaviour. You can only deallocate with delete things you allocated with new. This has nothing to do with the copy constructor.
name = new char[20];
name = "Hai";//_tcscpy(name,"Hai");
Here you are not copying the data into the memory allocated by new. Instead you are assigning a new value to pointer name which points at read-only location (in most cases). Since this memory was not allocated using new you can not do delete on it. Also, note that you have a memory leak here as the memory allocated using new char[20]; is never deleted.
The very same program, but in C++:
struct CopyCon
{
CopyCon(): name("HAI") {}
std::string name;
};
int main(int argc, char* argv[])
{
CopyCon obj1;
CopyCon obj2(obj1);
cout<<obj1.name<<endl;
cout<<obj2.name<<endl;
}
Mine works, is clear, and I typed less than you did ;)
What you do in that code is that you allocate a memory block for the name (assign an address to name pointer). Then you actually overwrite this address by the address of the string literal "Hai" (which ceases to exist after the constructor finishes). Thats why you get the error, since the destructor tries to free memory which does not belong to you. ( You did not allocate it ).