Search code examples
c++dynamic-memory-allocation

how to allocate memory int pointer array inside a function and delete the allocated memory in main.cpp


I am trying to allocate memory to a pointer to an array using a non-template type argument. But, I am getting a run time error at delete ptr in the main function.

#include <iostream>

using namespace std;

template<typename T, int SIZE>
void createArray(T** arrPtr) {
    *arrPtr = new T[SIZE];
    for (int i = 0; i < SIZE; i++)
        (*arrPtr[i]) = i + 1;
}

int main()
{
    constexpr int size = 3;
    int* ptr = nullptr;
    createArray<int, size>(&ptr);
    if (ptr == nullptr)
        return -1;
    for (int i = 0; i < size; i++)
        std::cout << *(ptr++) << " ";
    delete ptr;
    ptr = nullptr;

    return 0;
}

Solution

  • Within the function instead of this statement

    (*arrPtr[i]) = i + 1;
    

    you need to write

    (*arrPtr )[i] = i + 1;
    

    And in this for loop the original pointer ptr is being changed.

    for (int i = 0; i < size; i++)
        std::cout << *(ptr++) << " ";
    

    As a result in this statement

    delete ptr;
    

    there is used an invalid address of the allocated dynamically memory.

    Change the loop for example like

    for ( const int *p = ptr; p != ptr + size; )
        std::cout << *p++ << " ";