How to adjust padding of arrays


Pickle

Mega GP Mania
Joined
May 30, 2006
Messages
5,527
Location
Detroit, Michigan
Website
Visit site
Ive been working on a project that expects static arrays to be in sequential order in memory. A simple example would be something like this, but with much more data of course:

const char array1[] = { 0x01, 0x02, 0x3 };
const char array2[] = { 0x04, 0x05, 0x6 };
const char array3[] = { 0x07, 0x08, 0x9 };


What I found during debug is that the application would sometimes have padded zero's in between the arrays. Since the appication code works off the assumption the arrays are in memory one after the other the data would be offset.

The ideal solution im looking for is configuring gcc in a way that these are not padded. Does anyone know of any setting to control this? I have been searching but I havnt found anything that sounds like this.
 
on gcc, there is -mno-unaligned-access (for gcc 4.8+ or 4.7.3) or -munaligned-access (the oposite, for older version). Can this setting have an effect on automatic padding?
 
Last edited by a moderator:
Sequential order is one thing - and I think the standard says static/global arrays will be sequential - but you want those arrays to be contiguous which is a stronger requirement. There's nothing in the C standard which specifies that. Even a packed pragma or attribute wouldn't work since they're not part of some larger struct.

I would recommend making a big array then setting the other arrays as pointers into them:

Code:
const char _array[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
const char *array1 = array;
const char *array2 = array + 3;
const char *array3 = array + 6;
Or if you need statically initialized values and that doesn't work you can replace the array names with defines for offsets into the big array:

Code:
#define array1 (_array)
#define array2 (_array + 3)
#define array3 (_array + 6)
 
Last edited by a moderator:
I don't think the standard says anything, but #pragma pack   appears to do what's required, and seems to exist to achieve what some compilers assume automatically.
 
Last edited by a moderator:
Should be possible via a linker script too. Depends which is the easiest for you to implement/maintain. I have my fingers crossed you'll find a magical compiler flag, but I am not holding my breathe sadly.
 
ptitSeb: unaligned access isnt quite the same thing.

Exophase: understand that, but im hoping for an automatic solution since I currently have about a dozen apps and if i take an approach like that I will have to manually edit each one.

Just thinking as I was typing, maybe I could determine the padding by stepping byte by byte after the array until I match the data in the second array. Then I would have an offset that could be used when the access is made.

origimbo: as far as i can tell from my searching the pragma pack only applies to members in a structure, so no help in this case.
 
Back
Top