Boost logo

Boost :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2001-07-17 09:58:06

On Tuesday 17 July 2001 10:50, you wrote:
> Apologize for the question but
> I'm not very expert with C++.
> I don't understand if the following behaviour is correct.
> If the code is correct, is the problem caused by a
> compiler/std library's bug or by a boost's bug?
> Compiler: gcc 3.0, linux box
> Boost: 1.23.0
> The following code leads to a SIGSEG:
> --------------------------------------------
> #include <boost/smart_ptr.hpp>
> #include <vector>
> int main(void) {
> std::vector<boost::shared_ptr<int> >a;
> a.reserve(8);
> //a.resize(8);
> int * y;
> y = new int;
> a[0] = boost::shared_ptr<int>(y);
> return 0;
> };

The "reserve" method does not actually add any elements to the vector, it
merely reserves space so that later insertions don't require reallocation. So
at the line
a[0] = boost::shared_ptr<int>(y);

the vector a has no elements in it, so a[0] is attempting to access an
element that isn't there. The only reason you don't get a SIGSEGV when
accessing a[0] is that it points to allocated memory; the problem is that the
allocated memory hasn't been initialized yet.

When the a.resize(8) code is uncommented, it actually inserts or removes
elements until the container size is 8. Then a[0] is valid, and the code
works properly.


Boost list run by bdawes at, gregod at, cpdaniel at, john at