views:

221

answers:

3

Searched for a while, but I can't figure out why this would raise a bus error.

Any help would be much appreciated.

typedef struct {
   set<int> pages;
} someStruct;
...
void someFunction() {
   ...
   someStruct *a = createSomeStruct(); // just mallocs and returns
   a->pages.insert(5);
   ...
}
+7  A: 

malloc doesn't initialize the memory it allocates. try with new.

Maurice Perry
Thanks. That's what I get for trying to write C.
Mike Douglas
+1  A: 

Note also that "bus error" usually means "misaligned memory read." That is to say, trying to load an int32 from address 0x1001 will cause a bus error on many architectures (because the load-32-bit-word op expects an aligned address). That's usually a giveaway that you're trying to dereference a bogus pointer.

Maurice has clearly nailed the primary cause of the problem here, but thinking "bus error" -> "bogus pointer" can help track this sort of thing down in the future.

Crashworks
Same goes for "segfault". Ask me how I know :)
gbarry
+2  A: 

It is possible to initialise the set, if you really do have to use malloc for some reason:

typedef struct {
   set<int> pages;
} someStruct;
...
void someFunction() {
   ...
   someStruct *a = createSomeStruct();
   a->pages.insert(5);
   ...
}
...
someStruct *createSomeStruct(void) {
  someStruct *a = (someStruct *) malloc(sizeof(*a));
  new(&a->pages) set<int>;
  return a;
}
finnw