Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you always access suitably aligned buffer containing structure data in C?

Tags:

c

c11

I have data of a structure type in C:

typedef struct {
  type0 field0;
  type1 field1;
} foo_struct;

foo_struct foo;

Now let's say I have a buffer allocated in some fashion in virtual memory, of size sizeof(foo_struct)

char *buf = <some allocation method>

Then I copy the data from foo to buf, for example by memcpy.

Then I want to access the fields in buf like so:

((foo_struct *)buf)->fieldn

Is this guaranteed (by the C11 standard) to always work?

People in another question (on a different main topic) , seem to be saying, yes this is guaranteed to work, especially provided that buf is well-aligned, like, on a page boundary.

Yes it is practically assured. But I think, no matter how well it is "aligned", page boundary, or what not, there is no 100% guarantee by the standard. Is there?

like image 394
Mark Galeck Avatar asked Dec 26 '16 21:12

Mark Galeck


1 Answers

Can you always access suitably aligned buffer containing structure data in C?

If the buffer's in dynamic memory, then yes.

char *buf = malloc(1000000);
if(buf)
   ((foo_struct *)buf)->fieldn

is essentially like

foo_struct *buf = malloc(1000000);
if(buf)
    buf->fieldn

This is guaranteed to work.

If the buffer is statically allocated or automatic, then no. Aliasing rules (6.5p7) prevent you from doing:

/*static*/ _Alignas(foo_struct) char buf[100000000];
foo_struct* foo_p = &buf;
if(foo_p)
    foo_p->fieldn

even when the alignment of the buffer is sufficient.

(Note: 1 followed by many 0 == large enough)

like image 57
PSkocik Avatar answered Sep 27 '22 20:09

PSkocik