0

The maxPointers value may need to be different for your system, but allocating many unique_ptrs causes this application to crash and burn. Removing the definition of s and the cin operation gives some more room for pointer allocation.

Using MSVC 2015.

So, why does it crash and how to avoid it?

Thanks.

#include <iostream>
#include <vector>
#include <string>
#include <memory>
using namespace std;

int main(int argn, const char*argv[])
{
    int maxPointers = 37900;
    vector<unique_ptr<string>> pointerHolder;
    for (int i = 0; i < maxPointers; i++)
    {
        pointerHolder.push_back(make_unique<string>("pointer " + i));
    }
    cout << "done creating "<< maxPointers << " pointers" << endl;
    string s;
    cin >> s;
    for (int i = 0; i < maxPointers; i++)
    {
        pointerHolder.at(i).release();
    }
    pointerHolder.clear();
    cout << "done releasing " << maxPointers << " pointers" << endl;
    return EXIT_SUCCESS;
}
Florin
  • 3
  • 1
  • 4
    what is the result of `"pointer " + i` ? you probably meant `"pointer " + std::to_string(i)` – Piotr Skotnicki Sep 15 '15 at 14:25
  • Garbage. Yes, that's what I meant. Works now, thanks. – Florin Sep 15 '15 at 14:34
  • 1
    `("pointer " + i);` C++ is not Java or JavaScript. This does not concatenate strings. – PaulMcKenzie Sep 15 '15 at 14:35
  • BTW, why not use `std::vector` directly ? – Jarod42 Sep 15 '15 at 14:40
  • It's just a test case. I'm coming from a scripting background as it can be seen and I'm trying to familiarize myself with and understand some c++ features. – Florin Sep 15 '15 at 14:43
  • Get a [good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)! Learning C++ by trial-and-error is akin to dancing blindfolded close to a cliff. C++ contains undefined behavior, i.e. expressions that the compiler is allowed to translate into "fry your harddisk". In the best case your test case will crash, but it might also appear to work. – Fabio Fracassi Sep 15 '15 at 15:25

1 Answers1

4

The crash you encounter is because you build strings from garbage that results from call "pointer " + i. If you intend to concatenate literal "pointer" with an integer, then you'd need to convert that integer to std::string with std::to_string first:

make_unique<string>("pointer " + to_string(i));
//                               ~~~~~~~~~~~^
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160