Home > Back-end >  how to allocate memory int pointer array inside a function and delete the allocated memory in main.c
how to allocate memory int pointer array inside a function and delete the allocated memory in main.c

Time:01-28

I am tying to allocate a memory to a pointer to an array using non template type argument But, I am getting run time error at delete ptr in 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;
}

CodePudding user response:

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   << " ";
  •  Tags:  
  • Related