0

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 2.6.16.13-4-default 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));

    printf("Hello1\n");
    tmp->b.push_back(3);
    printf("Hello2\n");

    return 0;
}

Output:
Hello1
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).

4
Contributors
4
Replies
5
Views
10 Years
Discussion Span
Last Post by WaltP
Featured Replies
  • Also, if you're using C++, there's no reason you should be writing [inlinecode]typedef struct { ... } foo;[/inlinecode]. Just write [inlinecode]struct foo { ... };[/inlinecode]. Read More

0

> 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

1

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.
Take the time to help us to help you. Please be thoughtful and detailed and be sure to adhere to our posting rules.