Its possible that if I access memory map of a file, via pointer of a structure type which has hole, it may not map the structure elements to correct data. For eg.
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
typedef union{
int a;
char c[4];
}INT;
typedef struct{
char type;
INT data;
}RECORD;
int main(){
int fd;
RECORD *recPtr;
fd = open("./f1", O_RDWR);
if (fd == -1){
printf("Open Failed!\n");
}
printf("Size of RECORD: %d\n", sizeof(RECORD));
recPtr = (RECORD *)mmap(0, 2*sizeof(RECORD), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (recPtr == MAP_FAILED){
printf("Map Filaed!\n");
}
printf("type: %c, data: %c%c%c%c\n", recPtr->type, recPtr->data.c[0], recPtr->data.c[1], recPtr->data.c[2], recPtr->data.c[3]);
}
If the file "f1" contains the following data:
012345678
The above programs gives the output as
Size of RECORD: 8
type: 0, data: 4567
since the characters 123 are eaten up by the structure holes.
Is there a way to avoid this without using pragma pack directive and without changing the ordering of elements in the structure.