动态内存分配错误
Dynamic Memory allocation fault
下面给出的程序是为了使用动态分配的内存而创建的。
但是在数组中添加更多元素后,程序最终崩溃。
此代码清楚地显示了使用的概念和收到的错误。
那么有没有办法扩展动态分配数组的大小,因为在这里我的示例程序在分配内存后想要更大的大小
#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;
}
这就是瓦尔格林德所展示的
==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
- 这将导致向量自动为我们分配足够的新内存
- 并且分配将以对数方式发生,因此我们通常不需要担心性能损失
相关文章:
- vector.resize()中的分配错误
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 正在理解智能指针,但出现错误:未分配正在释放的指针
- 如何修复只读对象中成员的错误分配?
- 无法将错误分配给成员函数中"类型的实体"
- 分段错误分配函数结果
- 如何实现,错误分配中止而不是抛出异常
- C++代码错误分配
- 如何修复错误分配C++运行时错误
- 分段错误 - 分配类困难
- 带有数组类型表达式的错误分配
- Sprintf 缓冲区问题,错误分配给字符数组
- 而 (p=strtok(NULL, "," )) 警告:p可识别的错误分配
- 错误:分配只读位置“arr2.IntArray::operator[](1)”arr2[1]=24;
- std::映射错误分配错误
- 为什么"e.what()"打印"错误分配"?
- std::vector<const char *>的错误分配效果?
- 使用指向类的指针进行错误分配
- 错误:分配只读引用“__b”
- 向量错误分配错误 C++