I am trying to make a dynamic array that resizes continuously in runtime
In the following code the array should resize on any keypress It works for around three key presses but then suddenly crashes. What is the issue
#include<iostream>
int main(int argc, char const *argv[])
{
std::string b;
int size=1;
int * a= new int(1);
while (true)
{
std::cin>>b;
size++;
int *a1=new int(size);
for (size_t i = 0; i < size-1; i++)
a1[i]=a[i];
delete[] a;
a=NULL;
a=a1;
for (size_t i = 0; i < size; i++)
{
a[i]=i;
std::cout << a[i] << std::endl;
}
}
}
main().newandnew[].new int(size)creates a singularintvalue with the valuesize.new[size]allocatessizecountintvalues.newandnew[]at all for the next one or two years. Use STL containers instead. We're currently removing all occurrences of nakednewandnew[]in an older code searching for memory leaks.int* a = new int[size]();for a dynamic array (instead ofint* a = new int(size);which gives you a single integer with valuesize