0

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;
    }
  }    
}
  • 1
    If you're learning C++ that's great, but it's worth thinking in terms of *structs* and *classes* instead of just having at it in `main()`. – tadman Sep 30 '22 at 08:42
  • 4
    Tip: Don't mix up `new` and `new[]`. `new int(size)` creates a *singular* `int` value with the value `size`. `new[size]` allocates `size` count `int` values. – tadman Sep 30 '22 at 08:43
  • 1
    My tip: Don't use `new`and `new[]` at all for the next one or two years. Use STL containers instead. We're currently removing all occurrences of naked `new` and `new[]` in an older code searching for memory leaks. – jabaa Sep 30 '22 at 08:48
  • 1
    @jabaa That's great until you're giving some assignment to do this without the Standard Library. Some professors force you to bake your own food. – tadman Sep 30 '22 at 08:52
  • @tadman In that case, this would be a school assignment and should be marked as such. Special requirements should be mentioned in the question. – jabaa Sep 30 '22 at 08:53
  • @tadman then you write `namespace homework { template class vector ... }` *exactly once*, and #include it in all your homework – Caleth Sep 30 '22 at 08:55
  • @jabaa There's a lot of controversy over tagging questions as such, so I tend to just ask if it's for an assignment, or for production code instead. – tadman Sep 30 '22 at 08:55
  • 2
    Use `int* a = new int[size]();` for a dynamic array (instead of `int* a = new int(size);` which gives you a single integer with value `size` – doctorlove Sep 30 '22 at 09:11

1 Answers1

0

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.