Search code examples
c++arrayscharnew-operatordelete-operator

Crashing when trying to delete character array


When it gets to the delete portion where test2 needs to delete the String object it crashes. I am not sure why it crashes. It says "Debug Assertion failed!". Am I deleting the dynamically alloacted char array wrong?

strdrv.cpp:

#include <iostream>
#include <stdlib.h>
#include "strdrv.h"

int main() {
test2();
return 0;
}
void test2() {
cout << "2. Testing S2: String one arg (char *) constructor."
    << endl << endl;
csis << "2. Testing S2: String one arg (char *) constructor."
    << endl << endl;
String s2("ABC");
s2.print();
wait();
}

String.cpp:

#include "String.h"
#include <iostream>

using namespace std;
String::String(char* s) {
int sLength = 0;

for (int i = 0; s[i] != '\0'; i++) {
    sLength++;
}

buf = new char[sLength+1];
dynamicallyAlloc = true;
buf = s;

length = sLength;

/*buf[length] = '\0';*/ 
}

String::~String() {
if(dynamicallyAlloc)
    delete []buf;
}

String.h:

#ifndef _STRING_H
#define _STRING_H

#include <iostream>

using namespace std;

class String {
protected:
bool dynamicallyAlloc;
char nullChar;
int length;
char* buf;
void calculateStringLength();


public:
String();
String(char*);
String(char);
String(int);
String(const String&);
String(char, int);
~String();
int getLength() const;
char* getString() const;
String& operator=(const String&);
String& operator=(const char*);
String& operator+=(const String&);
String operator+() const;
char& operator[](int);
String& operator++();
String& operator--();
String operator++(int);
String operator--(int);
String substr(int, int);
void print();
friend String operator+(const String&, const String&);
friend String operator+(const String&, const char*);
friend String operator+(const char*, const String&);
friend String operator+(const String&, char);
friend String operator+(char, const String&);
friend char* operator+(const String&, int);
friend char* operator+(int, const String&);
friend int operator==(const String&, const String&);
friend int operator!=(const String&, const String&);
friend int operator<(const String&, const String&);
friend int operator<=(const String&, const String&);
friend int operator>(const String&, const String&);
friend int operator>=(const String&, const String&);
friend ostream& operator<<(ostream& os, const String& s1);
};

#endif

Solution

  • To copy the array contents, do not copy the pointer, Instead of

    buf = s;
    

    you want copy the contents

    memcpy(buf,s, sLength+1);
    

    This preserves the buf you have allocated for later deletion.