动态内存分配错误

时间:2018-06-12 16:59:27

标签: c++ c++14

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

但是在阵列中添加更多元素之后程序最终会崩溃。

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

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

#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上面显示的错误会增加....

1 个答案:

答案 0 :(得分:1)

问题是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
    • 这将导致向量自动为我们分配足够的新内存
    • 并且分配将以对数方式发生,因此我们通常不需要担心性能损失