Reputation: 143
I have the following code:
class Class
{
private:
char* str;
public:
Class(const char* src)
{
str = new char[strlen(src)];
strcpy(str,source);
}
~Class() {
delete [] str;
}
};
A main function calls the constructor with some string. Upon exiting, the runtime crashes on the destructor.The error message is:
pointer being freed was not allocated
How can I solve this
Upvotes: 0
Views: 3591
Reputation: 1513
The copy constructor should like this.
Class(const char* src)
{
str = new char[strlen(src) + 1];// +1 is missed in original code.
strcpy(str,source); // copy and append '\0'
}
Upvotes: 0
Reputation: 187
you must check a pointer to NULL , if os cant allocate smemory to array of char str . str being NULL, delete[] null pointer - problem.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
class Class
{
private:
char* str;
public:
Class(const char* src)
{
str = new char[strlen(src)];
if(str) {
strcpy(str,src);
}
}
char* getstr() { return str; }
~Class() {
if(str) {
delete [] str;
}
}
};
int main() {
Class te("sdfs\n");
printf("%s",te.getstr());
return 0;
}
Upvotes: -1
Reputation: 42899
Just look how nicer and safer your code becomes with use of std::string
:
class Class {
std::string str;
public:
Class(char const *src) : str(src) {}
};
And you don't need to worry about deleting memory, about allocating +1 character space for the \0
character at the end etc.
Upvotes: 4