dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: Help with stl list

  1. #1
    Join Date
    Jul 2005
    Posts
    1,030

    Help with stl list

    Here is my code,
    Code:
    struct _node
    {
    	DWORD d1;
    	DWORD d2;
    	char s[64];
    	DWORD d3;
    };
    
    typedef struct _node node;
    
    typedef list<node*> lnode;
    
    int main()
    {
        lnode* p = (lnode*)malloc(sizeof(lnode));
        lnode::iterator it = p->begin();
        return 0;
    }
    When lnode::iterator it = p->begin() is called, then it crashed. What happened? Thanks.

  2. #2
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Help with stl list

    Where are you getting this from? Seems like you are trying to learn C and C++ at the same time. You can't apply C programming to C++ types, because it won't work. Specifically, malloc only allocates space, it doesn't call a constructor like new does.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  3. #3
    Join Date
    Aug 2008
    Posts
    902

    Re: Help with stl list

    No need for typedef struct _node node, just name your struct node and leave out the typedef. Also, prefixing something with a _ or a __ is generally bad practice, as those should be reserved for the compiler.

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Help with stl list

    There's rarely a good reason to construct a std::list (or any STL container) on the heap. Prefer to put them on the stack (or inline in an object), you'll have fewer headaches.

  5. #5
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Help with stl list

    Code:
    int main()
    {
        lnode* p = (lnode*)malloc(sizeof(lnode));
        lnode::iterator it = p->begin();
        return 0;
    }
    When lnode::iterator it = p->begin() is called, then it crashed. What happened? Thanks.
    You didn't create a std::list<node*>. Nothing was constructed.

    All you did was allocate a bunch of bytes that equaled the sizeof() a std::list. Then you are trying to take these bytes and do std::list stuff on them.

    That's like me placing a bunch of parts in front of you that makes up a TV set, and expecting you to turn the TV on.

    Regards,

    Paul McKenzie

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)