Will elements of an array of type uint8_t always be packed into consecutive bytes of memory?

Viewed 229

I have a program, written in C, which processes 24-bit audio samples and packs them into RTP packets for transmission across a network.

My code defines a 'sample' as a union of an int32_t and an array uint8_t[4] such that I can perform arithmetic operations on the whole sample, but also access its individual bytes for packing into the L24 encoding scheme specified in RFC3190.

This approach is working well on both ARM and Intel based systems, compiling with gcc. However, I'm concerned that some other compiler or architecture might pad the uint8_t elements and therefore break my program. Is this a valid concern? If so, is there a better way I could be handling the audio data?

2 Answers

In statically declared arrays in C, values are stored in contiguous memory locations (thus pointer arithmetic can be used to iterate over the values). The effect of the union will only be that the two members start in the same memory location, which may or may not be aligned. Padding may occur to obtain this alignment, but not between the elements/values of the specific array.

Here is more about padding and alignment:

  1. http://c-faq.com/struct/padding.html
  2. http://c-faq.com/struct/align.html

Though the [u]intN_t types are optional, you should be safe using them.
See C11 p7.20.1.1

  1. The typedef name uintN_t designates an unsigned integer type with width N and no padding bits.

If you happen to use an implementation without the uint8_t it won't compile anyway.

Related