An example of memory management

Consider the following function that dynamically allocates an array of 420 shorts, reads their values from the user input, prints them in ascending order, and deallocates the array:

void print_sorted() {  short* arr{new short[420]};  for (int ix = 0; ix < 420; ++ix) {    std::cin >> arr[ix];  }  std::sort(arr, arr + 420);  for (int ix = 0; ix < 420; ++ix) {    std::cout << arr[ix];  }  delete arr; // very bad!}

We already made a mistake in the preceding code by using the wrong delete operator to deallocate the memory. To deallocate an array, we must use the delete[] operator, otherwise, the code leads to memory leaks. Here's how we illustrate the allocation of the array:

Let's say we release the space using delete instead ...

Get Expert C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.