Search code examples
c++dynamic-arrays

Why does my dynamic array in c++ crash after runtime?


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;
    }
  }    
}

Solution

  • C++ is not obvious, unfortunately.

    const int count = 3;
    
    int* x = new int[count]; // is array of 3 items which values are trash. 
    int* y = new int(count); // is one variable of int equaling 3.
    

    If there is array out of bounds, so it is Undefined Behavior in C++. The crash is one of the outcomes.

    Examples:

    x[ 0], x[1], x[2];// are well because x has 3 items but
    x[-1], x[3], x[4];// are UB;
    // also as 
    y[0]; // it's okey but 
    y[-1], y[1]; // there is the same problem.