I'm either missing something small or theres a BIG problem somewhere. The following code compiles sucessfully with g++ 4.1.0 under SuSE 10.1 i586 (Linux i686) but it gives a Segmentation Fault when I run it.

#include <stdio.h>
#include <list>

typedef struct    {
    std::list<int> b;
} data;

int main(int argc, char **argv)    {
    data *tmp = (data*)malloc(sizeof(data));


    return 0;

Segmentation fault

In fact, any operation on the list (and only the list, everything else works fine, even other members inside the same struct) results in some kind of segmentation fault as if the list needs initialization.

Any help will be appreciated (a lot).

> as if the list needs initialization.

I'd say that's dead on. If you use malloc the list's constructor isn't going to be called. Since this is C++ you should be using new/delete. You should also avoid using naked pointers most of the time, in favor of smart pointers like std::auto_ptr or a smart pointer provided by the boost library, which will automatically free resources through their destructor

Also, if you're using C++, there's no reason you should be writing typedef struct { ... } foo; . Just write struct foo { ... }; .

This article has been dead for over six months. Start a new discussion instead.