首页 > 解决方案 > 动态内存分配错误

问题描述

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

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

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

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

#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 所显示的

==5782== Memcheck, a memory error detector
==5782== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==5782== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==5782== Command: ./ec
==5782== 
Enter size of array: 2
Enter elements: 
1
2
Enter 1 more element: 3
==5782== Invalid write of size 4 
==5782==    at 0x4F3A890: std::istream::operator>>(int&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25
==5782==    by 0x108BC7: main (in /home/user1/ec)
==5782==  Address 0x5b8350c is 4 bytes after a block of size 8 alloc'd
==5782==    at 0x4C3089F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5782==    by 0x108B2A: main (in /home/user1/ec)
==5782== 
Want to enter more? y
Enter 1 more element: 4
Want to enter more? 

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

标签: c++c++14

解决方案


问题是n不断增长,但您的阵列没有。

这段代码调用了未定义的行为,幸好这给你带来了段错误:

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

arr只分配给存储n元素。简单地写过去不会自动重新分配。您正在寻找一个std::vector,它还将为您节省显式分配/取消分配任何东西的麻烦。

你可以像这样完成你想要的(未经测试):

#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;
}
  • 我们初始化向量来存储n元素
    • 这让我们cin >> arr[i]一开始就可以说
  • 我们emplace_back用于每个附加项目
    • 这将导致向量自动为我们分配足够的新内存
    • 并且分配会以对数方式发生,所以我们一般不用担心性能损失

推荐阅读