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;
    }
  }    
}
8
  • 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(). Commented Sep 30, 2022 at 8: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. Commented Sep 30, 2022 at 8:43
  • 1
    My tip: Don't use newand 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. Commented Sep 30, 2022 at 8: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. Commented Sep 30, 2022 at 8:52
  • 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 Commented Sep 30, 2022 at 9:11

1 Answer 1

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. 
Sign up to request clarification or add additional context in comments.

Comments