Segmentation fault...

Discussion in 'C++' started by deancoo, Feb 14, 2005.

  1. deancoo

    deancoo Guest

    Ok, I've got another one for ya. The code I've pasted below compiles fine
    but produces a seg fault. I've put a comment in where the seg fault gets
    tripped. Can someone please explain what I've done wrong. Thanks again for
    any help.


    #include <cstdlib>
    #include <iostream>
    #include <vector>

    using namespace std;

    class hand {
    vector<int> my_ints;

    class hand_vector {
    vector<hand> myhands;

    int main(int argc, char *argv[])


    hand_vector *myvector;
    hand v_stub;

    for (int i=1; i<=10; i++) {
    myvector->myhands.push_back(v_stub); // SEGMENTATION FAULT HERE


    vector<hand>::iterator j;

    for (j=myvector->myhands.begin(); j!=myvector->myhands.end(); j++) {


    delete myvector;

    return EXIT_SUCCESS;
    deancoo, Feb 14, 2005
    1. Advertisements

  2. Don't use a pointer when you need a local variable !

    Define myvector as:
    hand_vector myvector;
    and use it with '.':
    It will automatically be disposed of upon function exit.
    Ivan Vecerina, Feb 14, 2005
    1. Advertisements

  3. myvector is a pointer. It points to ... nowhere in particular
    So where is the hand_vector object, where myvector is supposed to point to?
    It was never allocated. All you have is a pointer that can point to such
    an object. But having a pointer and having the object itself are different
    things. It is as having a description of a Ferrari compared to having a
    Ferrari itself.
    Karl Heinz Buchegger, Feb 14, 2005
  4. deancoo

    deancoo Guest

    Doh! Thanks Karl, that's what happens when you work too late. Further,
    after correcting this problem by creating an instance on the heap with
    "new", I believe there is a memory leak of some sort. After deleting the
    "hand_vector" instance, not all memory is released (only about 30%). It
    appears to me as though the instances of "hand" are still hanging around.
    Are they not on the heap? Shouldn't they be released along with the
    "hand_vector" instance?


    deancoo, Feb 14, 2005
  5. What don't you use a debugger and put a breakpoint in the destructor
    of Hand and count the number of calls to the destructor to convince
    yourself you don't a leak, at least not ther.e

    Dave Townsend, Feb 16, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.