0

I have a problem inserting elements into a pointer to a vector of some elements I defined in my code (in this case Recipes). In some other parts of the code, using push_back seems to work fine, but if I use it in this code:

{
    Recipe defaultRec;
    this->recipes_ = new vector<Recipe>;
    this->recipes_->push_back(defaultRec);
}

I get the following error message:

"Unhandled exception at 0x01164031 in Assignment 2.exe: 0xC0000005: Access violation reading location 0xcccccce0"

The declaration of recipes_ is:

vector<Recipe>* recipes_;

Hope anyone can help me, thanks in advance.

Jota
  • 234
  • 2
  • 11
  • 4
    I predict you've broken the [rule of three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). Why are you using dynamic allocation of a `vector`? – GManNickG Mar 22 '11 at 23:22
  • 0xcccccce0 is 20 bytes away from 0xcccccccc (uninitialized value on the stack for a debug build with VC++), so it would seem you're dereferencing at some offset from an uninitialized pointer. Perhaps some other place uses recipes_ before it is initialized? – Peter Huene Mar 22 '11 at 23:53

2 Answers2

1

Your code looks fine to me. I'm sure the problem is somewhere else.

By the way, why do you use pointer to vector? Why not this:

vector<Recipe> recipes_; //member

Recipe defaultRec;
recipes_.push_back(defaultRec);

Atleast this saves you from allocation and deallocation. Besides, most likely, pointer to vector doesn't serve you any better than the above!

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • The problem is that due to design specifications, the function HAS to return a vector*. If not I would have already used your solution :( – Jota Mar 23 '11 at 03:05
  • 1
    @Jotamide: While I'm not sure about the function you're describing, I don't see why that would be at odds with what Nawaz has suggested (i.e. simply return the address of recipes_). – Peter Huene Mar 23 '11 at 04:12
1

There is nothing wrong with your code. The problem likely lies elsewhere. Problems like this are often caused by memory over writing such as writing past the end of an array or writing to an uninitialised memory location.

Goz
  • 61,365
  • 24
  • 124
  • 204