0

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

3 Answers 3

9

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

1
  • Thanks. That's what I get for trying to write C. Mar 2, 2009 at 9:04
2

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

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.

1
  • Same goes for "segfault". Ask me how I know :)
    – gbarry
    Apr 16, 2009 at 6:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.