[Solved] Dynamic Memory allocation fault


The issue is that n keeps growing, but your array does not.

This code invokes undefined behavior, which thankfully caused a segfault for you:

while(ch=='y')
{   n++;  cout<<"Enter 1 more element: ";   cin>>arr[n];
    cout<<"Want to enter more? ";       cin>>ch;
}

arr has only been allocated to store n elements. Simply writing past the end will not automatically reallocate. You’re looking for a std::vector, which will additionally save you the hassle of explicitly allocating/deallocating anything.

You can accomplish what you want like so (untested):

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int n;  char ch="y";
    cout<<"Enter size of array: ";
    cin>>n;
    std::vector<int> arr(n);
    cout<<"Enter elements: ";
    for(int i=0;i<n;++i) cin>>arr[i];

    //...

    while(ch=='y')
    {   n++;  cout<<"Enter 1 more element: ";
        int tmp;
        cin>>tmp;
        arr.emplace_back(tmp)
        cout<<"Want to enter more? ";       cin>>ch;
    }
    cout<<"All elements are: "; 
    for(int element : arr)
       cout<< element <<"  ";

    return 0;
}
  • We initialize the vector to store n elements
    • this allows us to say cin >> arr[i] at the start
  • We use emplace_back for each additional item
    • this will cause the vector to automatically allocate enough new memory for us
    • and the allocation will happen logarithmically so we generally don’t need to worry about performance loss

1

solved Dynamic Memory allocation fault