Question

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);
   ...
}
Was it helpful?

Solution

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

OTHER TIPS

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;
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top