unix - Using Contiguous Memory of C Struct Members -


before mark duplicate, please read question.

so may potentially stupid question bothering me. know, reading, many other questions fields in struct in c not guaranteed contiguous due padding added compiler. example, according c standard:

13/ within structure object, non-bit-field members , units in bit-fields reside have addresses increase in order in declared. pointer structure object, suitably converted, points initial member (or if member bit-field, unit in resides), , vice versa. there may unnamed padding within structure object, not @ beginning.

i working on writing program similar unix readelf , nm fun , involves lot of work dealing bytes @ specific offsets file read values. example, first 62 bytes of object file contains "file header". file header's bytes 0x00-0x04 encode int, while 0x20-0x28 encode pointer etc. however, noticed in original implementation of readelf.c programmer this:

first, declare struct (lets call elf_h) fields corresponding things in file header (i.e. first field int first 4 bytes in file header are, second char because bytes 0x04-0x05 in elf header encode char etc.). copy entire elf file memory , type case pointer points start of memory type elf_h. like:

file *file = fopen('filename', rb); void *start_of_file = malloc(/* size_of_file */); fread(start_of_file, 1, /* size_of_file */,file);  // copies entire file memory elf_h hdr = *(elf_h) start_of_file;               // type case pointer of type struct , dereference 

and after doing this, access each section of header using member variables of struct. instead of getting supposed @ byte 0x04 using pointer arithmetic, hdr.member2 (which in struct second member followed first 1 int).

how meant work if fields in struct aren't guaranteed contiguous?

the closest answer find here in example, members of struct of same type. in elf_h, of different types.

thank in advance :)

how meant work if fields in struct aren't guaranteed contiguous?

the standard doesn't require structs contiguous, doesn't mean structs laid out @ random or in unpredictable ways. specific compiler , linker being used generate binary in specified way, dictated application binary interface or abi. happens on gnu/linux machine, elf abi corresponds how gcc lay out , access struct.

in other words, can predict whether method describe work given abi / compiler / linker combination. it's not guaranteed work standard, might guaranteed work compatibility of abis.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -