Search code examples
c++delete-operator

C++ Beginner Delete code


I am attempting to dynamically allocate memory to the heap and then delete the allocated memory. Below is the code that is giving me a hard time:

// String.cpp
#include "String.h"

String::String() {}

String::String(char* source)
{
 this->Size = this->GetSize(source);
 this->CharArray = new char[this->Size + 1];
 int i = 0;
 for (; i < this->Size; i++) this->CharArray[i] = source[i];
     this->CharArray[i] = '\0';
}

int String::GetSize(const char * source)
{
 int i = 0;
        for (; source[i] != '\0'; i++);
        return i;
}

String::~String()
{
 delete[] this->CharArray;
}

Here is the error I get when the compiler tries to delete the CharArray:

0xC0000005: Access violation reading location 0xccccccc0.

And here is the last call on the stack:

msvcr100d.dll!operator delete(void * pUserData) Line 52 + 0x3 bytes C++

I am fairly certain the error exists within this piece of code but will provide you with any other information needed. Oh yeah, using VS 2010 for XP.

Edit: Heres my String.h

// String.h - string class
#pragma once

#define NOT_FOUND -1

class String
{
public:
    String();
    String(char* source);
    static int GetSize(const char * source);
    int Find(const char* aChar, int startPosition = 0);
    ~String();
private:
    char* CharArray;
    int Size;
};

Solution

  • Change your default ctor; given the error you're getting, the delete call is trying to delete a pointer that has never been initialized.

    String::String() : Size(0), CharArray(NULL) {}
    

    Also, beware of the "copy constructor". You might want to make it private just to be sure you're not triggering it implicitly. (It doesn't need to be implemented if you don't intend to call it, just stick the function prototype into your class definition.) Might as well similarly "disable" the assignment operator.

    class String
    {
       // other stuff
    
    private:
        String(String&);
        String& operator=(String&);
    };
    

    This addition fulfills the "Rule of Three," which says that if any class needs a destructor, a copy constructor, or an assignment operator, it probably needs all three.

    Edit: see http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29