-3

After uncommenting delete[] array; I'm getting this error CRT detected that the application wrote to memory after end of heap buffer

What do I have to do to correct this problem?

#include <iostream>
using namespace std;

int main(){
    char ch;
    char* array = new char[0];
    int array_index = 0;
    while(cin>>ch){
        if(ch != '!'){
            array[array_index++] = ch;
        }else{
            break;
        }
    }

    //delete[ ] array;

}
melpomene
  • 84,125
  • 8
  • 85
  • 148

1 Answers1

4

What do I have to do to correct this problem?

You have to allocate sufficient memory to store your characters. Zero chars is not enough:

char* array = new char[0];
                      ^^^

My advice would be to use std::string. It will take care of memory management for you.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • @AshotNavasardyan there is a great example at the bottom of [this documentation page for `std::getline`](https://en.cppreference.com/w/cpp/string/basic_string/getline). Note that this example is looking for the end of a line , but it is easily changed to look for a `'!'` instead. – user4581301 Jul 20 '19 at 15:14
  • @AshotNavasardyan Get a [good book](https://stackoverflow.com/q/388242/9254539) that teaches C++ standard library containers early on instead of teaching the hard and less useful things first. – eesiraed Jul 20 '19 at 15:16