在C 中分配内存时出错
Error when allocating memory in c++
i使用CPP编写一个程序,用CIN读取字符串并将其保存在分配的内存中。我需要做的一项额外工作是处理输入大小超出预期的情况。当我测试代码时,它不会显示最终内存保存的内容,无法自动终止。这是代码。
#include <iostream>
#include <memory>
using namespace std;
int main(){
allocator<string> sa;
cout << "Please input the amount of words" << endl;
int count;
cin >> count;
auto p = sa.allocate(count);
cout << "Please input the text" << endl;
string s;
auto q = p;
while(cin >> s){
if (q == p + count) {
auto p2 = sa.allocate(count * 2);
auto q2 = uninitialized_copy_n(p, count, p2);
while (q != p) {
sa.destroy(--q);
}
sa.deallocate(p, count);
p = p2;
q = q2;
count *= 2;
}
sa.construct(q++, s);
}
for (auto pr = p; pr != q; ++pr) {
cout << *pr << " ";
}
cout << endl;
while (q != p) {
sa.destroy(--q);
}
sa.deallocate(p, count);
return 0;
}
为什么使用分配器?此模板不应直接在代码中使用。它假定用于调整STL容器的行为。您是新手,所以不要触摸它。此功能适用于高级开发人员在极端情况下使用。
只需使用std::vector<string>
,它具有您需要的所有功能。
cout << "Please input the amount of words" << endl;
int count;
cin >> count;
auto v = vector<string> {};
v.reserve(count);
string s;
while (cin >> s)
{
v.push_back(s);
}
相关文章:
- 将字符串存储在c++中的稳定内存中
- 访问者访问变体并返回不同类型时出错
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 如何在多写入器情况下对文件支持的共享内存中的大页面出错
- 在C 中分配内存时出错
- 读取字符串 的字符时出错.分配内存
- c++ 数组和内存出错
- 获取应用程序的内存使用情况时出错
- 使用calloc分配内存时出错(释放堆块XXX后在YYY修改)
- 为双精度值分配内存时出错
- 在链表的开头插入时读取内存时出错
- 为二维数组动态分配内存时出错
- 释放内存时出错
- 将矢量bool复制到CUDA内存时出错
- Std::out_of_range在内存位置0x0043f7c4.使用矢量和输入文件时出错
- 试图构建最小内存时出错
- 如果使用memcpy,释放内存时出错
- 使用内存出错
- 尝试获取C++上的当前进程内存大小时出错,MinGW
- 如何避免访问已删除的内存块时出错