在c ++中分配内存时出错

时间:2017-05-06 09:44:11

标签: c++

我使用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;
}

1 个答案:

答案 0 :(得分:5)

为什么使用allocator?该模板不应直接在代码中使用。它假设用于调整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);
}