I have created a class of MyString. My code was working just fine but when I wrote the destructor for my class it is giving me the error at delete keyword. Please help me out where is the problem and what is the solution.
MyString Header File
#pragma once
#ifndef MYSTRING_H
#define MYSTRING_H
class MyString
{
private:
char* str;
int length;
public:
MyString();
MyString(const char*);
~MyString();
};
#endif
MyString CPP File
#include "MyString.h"
#include <iostream>
using namespace std;
MyString::MyString() {
length = 0;
str = new char[length];
str[length] = '\0';
}
MyString::MyString(const char* cString) {
length=strlen(cString);
str = new char[length];
for (int i = 0; i < length; i )
str[i] = cString[i];
str[length] = '\0';
}
MyString::~MyString() {
delete[] str;
str = nullptr;
length = 0;
}
Main CPP File
#include "MyString.h"
#include <iostream>
using namespace std;
int main() {
//MyString s1;
MyString s2("OOP is Fun!!");
char name[15] = "Pakistan";
MyString s3(name);
return 0;
}
CodePudding user response:
length = 0;
str = new char[length];
The Golden Rule Of Computer Programming states: "your computer always does exactly what you tell it to do instead of what you want it to do". Here, this is exactly what you told your computer: allocate an array with 0 bytes. In other words, an empty array that does not contain anything at all. In other words: absolutely nothing was allocated.
str[length] = '\0';
This sets the first byte in the array to 0. Since nothing was allocated, this is undefined behavior, and your memory corruption, right here. You should've allocated 1 byte instead of 0 bytes.
The other constructor has the same defect. Since '\0'
is a plain char
, no different than any other char
, like 'A'
, or '0'
, your code must always allocate an extra character for it, in addition to all other characters in the actual text string.