c++ - 动态内存分配错误
问题描述
下面给出的程序是为了使用动态分配的内存而创建的......
但在数组中添加更多元素后,程序最终崩溃。
此代码清楚地显示了使用的概念和收到的错误。
那么有没有办法扩展动态分配数组的大小,因为这里我的示例程序在分配内存后想要更大的大小
#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 错误会增加......
解决方案
问题是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
用于每个附加项目- 这将导致向量自动为我们分配足够的新内存
- 并且分配会以对数方式发生,所以我们一般不用担心性能损失
推荐阅读
- github-classroom - 如何自动将自动评分文件复制到学生的存储库中?
- javascript - 使用 Chart.js 显示比赛单圈时间和位置
- python - python中的频率与总数条形图
- installation - magento 设置错误:升级 - 元素“路由”:缺少子元素。预期是(资源)
- javascript - onClick 方法适用于第二次点击。但它应该在第一次点击时起作用
- excel - 所有行中的 Excel 查找值,而不仅仅是第一个匹配项
- elasticsearch - RestHighLevelClient 弹性搜索 Java 客户端需要更多时间进行搜索查询
- sql-server - 如何使用 T-SQL 将 Row 拆分为多列
- three.js - 合并形状的相同图像纹理
- regex - 正则表达式用于提取字符串中的数字而不是单词而不是用符号分隔?