Search code examples
c++pointersboostshared-ptr

Passing shared_array<T> argument


The code below crashes when uncommented and it seems that shared_array<> argument in get() is problematic.

print() doesn't seem to crash at least for now...

What is the correct way to pass shared_array<> arguments?

#include <iostream>
#include <cstring>
#include <boost/shared_array.hpp>
using namespace std;
using namespace boost;

shared_array<wchar_t> get(const wchar_t* s) {
//shared_array<wchar_t> get(const shared_array<wchar_t>& s) {

    size_t size = wcslen(s);
    //size_t size = wcslen(s.get());

    shared_array<wchar_t> text(new wchar_t[size+1]);

    wcsncpy(text.get(), s, size+1);
    //wcsncpy(text.get(), s.get(), size+1);

    return text;
}

void print(shared_array<wchar_t> text) {
    wcout << text.get() << endl;
}

int wmain(int argc, wchar_t *argv[]) {
    //shared_array<wchar_t> param(argv[1]);

    shared_array<wchar_t> text = get(argv[1]);
    //shared_array<wchar_t> text = get(param);

    print(text);
    //print(text.get()); 
}

Edit: Thanks. So the key point here is that I should always use only new/new[] when using boost::shared_ptr/array.

The main function fixed:

int wmain(int argc, wchar_t *argv[]) {
    size_t szArg = wcslen(argv[1]);
    wchar_t* paramBuf = new wchar_t[szArg+1];
    wcscpy_s(paramBuf, szArg+1, argv[1]);
    shared_array<wchar_t> param(paramBuf);

    shared_array<wchar_t> text = get(param);

    print(text);
}

Actually at first I allocated paramBuf in the stack so I couldn't find the mistake.

WRONG:    
int wmain(...) {
    wchar_t paramBuf[100];
    wcscpy_s(paramBuf, 100, argv[1]);
    ...
}

Solution

  • The problem is at the line:

    shared_array<wchar_t> param(argv[1]);
    

    shared_array requires to be initialized with a pointer to an array allocated with new[] but argv[1] is just an c-string, so when it goes out of scope (the variable param that is) the shared_array's destructor calls delete[] on argv[1] which is not allowed.