Diagnosing SIGBUS error on OS X Yosemite

2019-09-11 07:51发布

问题:

I'm attempting to convert some code to run on OS X and having problems with some of the low-level memory writing code (which works on Linux/Windows platforms).

Specifically the method being called is:

void Dset_mem_write_i1B(void* ptr,int val) {
  unsigned char* p=(unsigned char*)ptr;
  *p=(val)&0xFF;
}

The relevant test code (GTest) is:

TEST(DsetMemIoTest, test_write) {
  const char mem[4] = "";
  void* vmem = (void*)mem;
  int mem_read = 0;
  int to_write = 0;

  to_write = 'a';
  Dset_mem_write_i1B(vmem, to_write);
  mem_read = Dset_mem_read_i1B(vmem);
  EXPECT_EQ('a', (char)mem_read);

When running in gdb (installed using homebrew) I'm getting:

Program received signal SIGBUS, Bus error.
0x0000000100009213 in Dset_mem_write_i1B (ptr=0x100054c95 <DsetMemIoTest_test_write_Test::TestBody()::mem>, val=97) at ...
78        *p=(val)&0xFF;

I tried adding explicit casts which didn't seem to make a difference.

I can't find any clue as to why this would fail on OS X. Any help on how to diagnose this would be appreciated.