Bus error with allocated memory on a heap

后端 未结 3 432
情话喂你
情话喂你 2021-01-28 04:45

I have Bus Error in such code:

char* mem_original;
int int_var = 987411;
mem_original = new char [250];
memcpy(&mem_original[250-sizeof(int)         


        
3条回答
  •  梦毁少年i
    2021-01-28 05:40

    Although I don’t have access to a SPARC right now to test this, I’m pretty sure from my experiences on that platform that this line is your problem:

    const unsigned char *location = mem_u_const + 250 - sizeof(int);
    

    The mem_u_const block was originally allocated by new for an array of characters. Since sizeof(unsigned char) is 1 and sizeof(int) is 4, you are adding 246 bytes. This is not a multiple of 4.

    On SPARC, the CPU can only read 4-byte words if they are aligned to 4-byte boundaries. Your attempt to read a misaligned word is what causes the bus error.

    I recommend allocating a struct with an array of unsigned char followed by an int, rather than a bunch of pointer math and casts like the one that caused this bug.

提交回复
热议问题