Memory allocation error in C ++

I am writing a program using cpp to read lines from cin and store them in allocated memory. The additional work I need to do is related to the circumstance when the input is larger than expected. When I test the code, it doesn't display the contents of the last saved memory, can't auto-terminate. Here is the code.

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

      

+3


source to share


1 answer


Why are you using a dispenser? This template should not be used directly in your code. It is intended to be used to customize the behavior of STL containers. You are a beginner, so don't touch it. This feature is that advanced developers are used as a last resort.

Just use std::vector<string>

, you have all the functions you need.



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

      

+6


source







All Articles