0

I'm trying to do something similar to the code snippet below but the program crashes before main exits with

HEAP Invalid address specified to RtlValidateHeap

The idea is to have a function that creates a struct, fills a member array of the struct and returns the struct.

struct Sentence
{
    int char_count;
    char* characters;
    Sentence() {}
    Sentence(int input_char_count) : char_count(input_char_count) {
        characters = new char[char_count];
    }

    ~Sentence()
    {
        delete[] characters;
    }
};


Sentence write_alphabet(int length)
{
    Sentence s(length);

    for (int i = 0; i < length; i++)
        s.characters[i] = 'a' + i;

    return s;
}


int main()
{

    Sentence a_to_m;

    a_to_m = write_alphabet(length);
}

I created characters with new so it should be ok to delete[] right?

trips
  • 1
  • 7
    You should follow the [rule of 3](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) (which is now rule of 5), because your class's default copy semantics will burn you, you'll get a double deletion of that array. If your class will manage its own raw array with `new[]` and `delete[]` then each instance of your class needs its own copy, which you'd have to write. You get that for free if you switch to `std::string` or even `std::vector` – Cory Kramer Mar 31 '21 at 19:48
  • 2
    Unless this is homework where you have to implement this on your own, look up `std::string`. – Jerry Coffin Mar 31 '21 at 19:55

0 Answers0