0

So i need to create an array of dynamic size containing pairs of objects and I have the following piece of code:

#include <utility>
#include <iostream>
#include <string>

using namespace std;

int main() {

    cout << "Hey #1" << endl;

    pair<string, int> *array;

    array = new pair<string, int>[4];

    cout << "Hey #2" << endl;

    delete array;

    cout << "Hey #3" << endl;
}

and the output I get is

Hey #1
Hey #2
Segmentation fault (core dumped)

which means that something goes wrong when the delete operator gets called?

What am I missing here? Any help would be appreciated!

Da Mike
  • 447
  • 4
  • 17
  • 1
    `array = new pair[4];` -- What are you really trying to accomplish here? Second, do not call your variable `array`, as there is a `std::array` class that exists in standard C++. – PaulMcKenzie Mar 19 '20 at 13:37
  • @PaulMcKenzie Create an array containing 4 pairs. – Da Mike Mar 19 '20 at 13:38
  • 1
    Since you stated you are creating an array, what form of `delete` should you be using when deleting an array? Also `std::array, 4>` would avoid having to use `new`. – PaulMcKenzie Mar 19 '20 at 13:39
  • @PaulMcKenzie For sure not the one I was using. Thanks! – Da Mike Mar 19 '20 at 13:41

3 Answers3

4

You need to use the operator delete []

delete [] array;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
4

When you allocate objects with new, you need to free them with delete; when you allocate objects with new[] you need to free them with delete[]. Change your code to:

delete[] array;
Ðаn
  • 10,934
  • 11
  • 59
  • 95
DeducibleSteak
  • 1,398
  • 11
  • 23
4

When deleting a dynamic array use delete[] instead of delete to delete multiple dynamically allocated data. Hope this solves your problem.

Ðаn
  • 10,934
  • 11
  • 59
  • 95
Hussam
  • 93
  • 5