As far as I know, there is no exact alternative for the realloc of C in C++ like the new for malloc. However, when I use the realloc in C++ to alter the memory allocated by the new operator, it works fine.
Is it safe to use those two (new and realloc) like I do in the codes below or it can lead to some problems?
#include <iostream>
#include <cstdlib>
int main()
{
int size = 5;
int * arr = new int[size]{ 1,3,5,7,9 };
for (int i = 0; i < size; i++)
std::cout << *(arr + i) << (i < size - 1 ? ' ' : '\n');
size++;
arr = (int*)realloc(arr, size * sizeof(int));
*(arr + size - 1) = 11;
for (int i = 0; i < size; i++)
std::cout << *(arr + i) << (i < size - 1 ? ' ' : '\n');
delete[] arr;
//free(arr);
std::cin.get();
return 0;
}
Also, which operator should I use in such a case to free the memory: delete[] of free()?