How to delete a pointer after returning its value inside a function

Dynamic arrays are freed using delete[]:

char* block = ReadBlock(...);
// ... do stuff
delete[] block;

Ideally however you don't use manual memory management here:

std::vector<char> ReadBlock(std::fstream& stream, int size) {
    std::vector<char> memblock(size);
    stream.read(&memblock[0], size);
    return memblock;
}

You can call:

char * block = ReadBlock(stream, size);
delete [] block;

But... that's a lot of heap allocation for no gain. Consider taking this approach

char *block = new char[size];
while (...) {
  stream.read(block, size);
}
delete [] block;

*Note, if size can be a compile time constant, you can just stack allocate block.


I had a similar question, and produced a simple program to demonstrate why calling delete [] outside a function will still deallocate the memory that was allocated within the function:

#include <iostream>
#include <vector>

using namespace std;

int *allocatememory()

{
    int *temppointer = new int[4]{0, 1, 2, 3};
    cout << "The location of the pointer temppointer is " << &temppointer << ". Locations pointed to by temppointer:\n";
    for (int x = 0; x < 4; x++)
        cout << &temppointer[x] << " holds the value " << temppointer[x] << ".\n";
    return temppointer;
}

int main()
{
    int *mainpointer = allocatememory();
    cout << "The location of the pointer mainpointer is " << &mainpointer << ". Locations pointed to by mainpointer:\n";
    for (int x = 0; x < 4; x++)
        cout << &mainpointer[x] << " holds the value " << mainpointer[x] << ".\n";

    delete[] mainpointer;
}

Here was the resulting readout from this program on my terminal:

The location of the pointer temppointer is 0x61fdd0. Locations pointed to by temppointer:

0xfb1f20 holds the value 0.

0xfb1f24 holds the value 1.

0xfb1f28 holds the value 2.

0xfb1f2c holds the value 3.

The location of the pointer mainpointer is 0x61fe10. Locations pointed to by mainpointer:

0xfb1f20 holds the value 0.

0xfb1f24 holds the value 1.

0xfb1f28 holds the value 2.

0xfb1f2c holds the value 3.

This readout demonstrates that although temppointer (created within the allocatememory function) and mainpointer have different values, they point to memory at the same location. This demonstrates why calling delete[] for mainpointer will also deallocate the memory that temppointer had pointed to, as that memory is in the same location.


Just delete[] the return value from this function when you've finished with it. It doesn't matter that you're deleting it from outside. Just don't delete it before you finish using it.