EXC_BAD_ACCESS related to alignment structure?

In an iOS app, I have a structure that looks like this:

typedef struct _Pixel {
  signed char r;
  signed char g;
  signed char b;
} Pixel;

In my code, I allocate an array of them using calloc:

Pixel* buff = calloc(width * height, sizeof(Pixel));

Now this works fine in the simulator, but on the device, if I try to access buff[width * height - 1](i.e. the last element in buff), I get EXC_BAD_ACCESS.

This didn't make sense to me, so after a few hours of debugging, I wondered if this was some kind of alignment problem, so by the whim I tried:

typedef struct _Pixel {
  signed char r;
  signed char g;
  signed char b;
  signed char padding;
} Pixel;

making the pixel size equal to two.

EXC_BAD_ACCESS, . - , ? , , ( , , ).

+5
2

EXC_BAD_ACCESS . x86, ARM , .

, #pragma push, #pragma pack(n) #pragma pop .

. http://tedlogan.com/techblog2.html

+3

. 4 , (, double). , 3 4. , 4 - .

, "int" , 8. - , int.

typedef struct {

signed char r;
signed char g;
signed char b;
}MyType;

MyType *type = (MyType *)calloc(20, sizeof(MyType));
printf("size: %ld", sizeof(MyType));
printf("size: %ld", sizeof(type[0]));

printf 4, 3. 4 , 3 . int .

typedef struct {

signed char r;
signed char g;
signed char b;

int i;           // New int element added here
}MyType;

MyType *type = (MyType *)calloc(20, sizeof(MyType));
printf("size: %ld", sizeof(MyType));
printf("size: %ld", sizeof(type[0]));

printf- 8. char int, . , ,

typedef struct {

signed char r;
signed char g;
signed char b;

char padding;    // Padding byte allocated to keep alignment.

int i;
}MyType;

, , - 3 .

.

+2

All Articles