0

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.

akosky
  • 834
  • 9
  • 5
  • 2
    SIGBUS generally means that a pointer is not properly aligned for the size of value you're accessing through it. – Barmar Sep 09 '15 at 20:16
  • Although that makes no sense when writing a single char, since there are no alignment requirements for `char`. – Barmar Sep 09 '15 at 20:16
  • 2
    The problem is the `const` keyword in `const char mem[4]`. You're declaring `mem` as read-only, and then trying to write to it. – user3386109 Sep 09 '15 at 20:24
  • 1
    Since you're writing to `mem`, which is declared `const char`, it's possible that the memory is not writable in this case, whereas it might be under the other platforms? – Joe Sewell Sep 09 '15 at 20:26
  • Thanks! This was indeed the problem. I was looking for issues with pointer alignment, but it didn't notice that the memory was declared as const. It's interesting that it didn't show up on other platforms. – akosky Sep 09 '15 at 20:32

0 Answers0