在C 中分配内存时出错

Error when allocating memory in c++

本文关键字:出错 内存 分配      更新时间:2023-10-16

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);
}