创建下面给出的程序是为了使用动态分配的内存....
但是在阵列中添加更多元素之后程序最终会崩溃。
此代码清楚地显示了使用的概念和收到的错误。
所以有没有办法扩展动态分配的数组的大小,因为我的示例程序在分配内存后需要更多的大小
#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上面显示的错误会增加....
答案 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