C++ 动态内存分配故障

C++ 动态内存分配故障,c++,c++14,C++,C++14,下面给出的程序是为使用动态分配的内存而创建的 但在数组中添加更多元素后,程序最终崩溃 此代码清楚地显示了使用的概念和收到的错误 因此,没有办法扩展动态分配的数组的大小,因为在这里,我的示例程序在分配内存后需要更大的大小 #include<iostream> using namespace std; int main() { int n; char ch='y'; cout<<"Enter size of array: "; cin>>

下面给出的程序是为使用动态分配的内存而创建的

但在数组中添加更多元素后,程序最终崩溃

此代码清楚地显示了使用的概念和收到的错误

因此,没有办法扩展动态分配的数组的大小,因为在这里,我的示例程序在分配内存后需要更大的大小

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

    // above code works fine, the below creates problem

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

    delete []arr;
    return 0;
}

当valgrind在任何大型程序中使用该概念时,上面显示的错误都会增加。

问题在于
n
不断增长,但您的数组却没有

此代码调用未定义的行为,谢天谢地,这为您造成了segfault:

while(ch=='y')
{   n++;  cout<<"Enter 1 more element: ";   cin>>arr[n];
    cout<<"Want to enter more? ";       cin>>ch;
}
  • 我们初始化向量以存储
    n
    元素
    • 这允许我们在开始时说
      cin>>arr[i]
  • 我们对每个附加项目使用
    emplace\u back
    • 这将导致向量自动为我们分配足够的新内存
    • 分配将以对数方式进行,因此我们通常不需要担心性能损失

提供一个。你为(int i=n;做
,然后你做:
arr[i]
。这是一个越界访问,最后一个有效索引是
n-1
n+=1;
n
不断变大。分配的数组没有。这个大炸弹不是好主意。
new int[n]创建的数组的固定大小等于在创建数组时代码<> >代码>的值。在任何情况下数组的大小都不会改变。@根用户不能在C++中调整数组的大小。必须创建一个新数组,它具有所需的大小和旧数组中的值的拷贝。或者你。谢谢,上面的代码就是我所需要的。只需将“arr.emplace_back(tmp);”替换为“arr.emplace_back(tmp)”(不带分号)
while(ch=='y')
{   n++;  cout<<"Enter 1 more element: ";   cin>>arr[n];
    cout<<"Want to enter more? ";       cin>>ch;
}
#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;
}