user1489443
user1489443

Reputation: 11

Vector push_back error

So this is the situation.

I have a class

Class L_FullQuote
{
    private:
    vector<int> time;
    ..
}

and

Class B
{

    L_FullQuote *Symbols[100];

    void handle message()

}

Inside handle msg i have this statement

Symbols[i]->time.push_back(2);

the code builds fine..but when i use the generated dll. the application just crashes..sometimes it takes me to a nxt poiner error in vector..but mostly the whole application just crashes. It works fine without that line.

Please help

Thanks

Upvotes: 1

Views: 4317

Answers (3)

Chad
Chad

Reputation: 19032

You're already using vector, so why not take it one step further? Using std::vector will allow you to focus on writing your functionality, rather than worrying about memory management.

This example differs slightly from what you originally posted. Your original question class B has an array of 100 pointers that each must be initialized. In the example below, we create a std::vector of L_FullQuote objects that is initially sized to 100 objects in the constructor.

class L_FullQuote
{
public:
    vector<int> time;
};

class B
{
public:
    // Initialize Symbols with 100 L_FullQuote objects
    B() : Symbols(100)
    {
    }

    std::vector<L_FullQuote> Symbols;

    void handle_message()
    {
       Symbols[i].time.push_back(2);
       // other stuff...
    }

};

Upvotes: 2

Ed Swangren
Ed Swangren

Reputation: 124632

L_FullQuote *Symbols[100];

Here you declare an array of pointer to L_FullQuote, but you never initialize any of the pointers, so when you call:

Symbols[i]->...

You are dereferencing an invalid pointer. Also note that you have declared time as private (though your code wouldn't even compile this way, s B as a friend of A I assume?)

Simply declaring an array of pointers does not initialize each element to point to a valid object. You need to initialize each one, something like:

for(int i = 0; i < 100; ++i) {
    Symbols[i] = new L_FullQuote();
}

Only then do you have an array full of valid pointers. Don't forget to deallocate them though!

Upvotes: 1

kobra
kobra

Reputation: 1315

time is private member of class L_FullQuote, from class B you don't have access to that field

Upvotes: -1

Related Questions