Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

The benefits and limitations of flexible array members

September 29, 2022
Serge Guelton
Related topics:
CompilersC, C#, C++Security
Related products:
Red Hat Enterprise Linux

Share:

    Flexible array members (FAM) is an extension of C89 standardized in C99. This article discusses how flexible array members offer convenience and improve performance and how compiler implementations can generate complications.

    FAM makes it possible to declare a struct with a dynamic size while keeping a flat memory layout. This is a textbook example:

    struct fam {
    
         int size;
    
         double data[ ];
    
    };

    The data array starts empty and will be loaded later, perhaps many times. Presumably, the programmer uses the size member to hold the current number of elements and updates that variable with each change to the data size.

    Flexible array members vs. pointer implementation

    Flexible array members allow faster allocation, better locality, and solid code generation. The feature is an alternative to a more traditional declaration of data as a pointer:

    struct fam {
    
         int size;
    
         double *data;
    
    };

    With the pointer implementation, adding an array element requires an extra load initializing the structure on the heap. Each element added to the array requires two allocations for the object and its data member. The process results in fragmented memory between the object and the area pointed at by data.

    Standard flexible array member behavior

    The C99 standard, section 6.7.2.1.16, defines flexible array members. A struct with a flexible array member behaves in interesting ways.

    It is legal to access any index of fam::data, providing enough memory has been allocated:

    struct fam * f = malloc(sizeof(struct fam) + sizeof(double[n]));
    
    f - > size = n;

    The sizeof operator behaves as if the FAM had zero elements but accounts for the padding required to position it correctly. For instance, sizeof(struct {char c; float d[];} is unlikely to be equal to sizeof(char) because of the padding required to correctly position d.

    The assignment operator does not copy the flexible array member, which probably explains why that operator is not part of the C++ standard.

    This would be the end of this post if there were no nonconformant compiler extensions.

    Nonconforming compiler extensions

    Flexible array members are supported only by GCC and Clang in C89 and C++ as extensions. The extensions use alternate syntax, sometimes called a struct hack.

    struct fam_extension {
    
         int size;
    
         double data[0];
    
    };

    Alternatively, you can specify:

    struct fam_extension {
    
         int size;
    
         double data[1];
    
    };

    As it turns out, this syntax extended to any array size due to prior art, as suggested in the FreeBSD developers handbook, section 7.5.1.1.2 sockaddr:

    struct sockaddr {
    
    unsigned char sa_len; /* total length */
    
    sa_family_t sa_family; /* address family */
    
    char sa_data[14]; /* actually longer; address value */
    
    };

    Note that using an array size different from 0 for the FAM makes the allocation idiom more complex because one needs to subtract the size of the FAM:

    struct fam * f = malloc(sizeof(struct sockaddr) + sizeof(char[n]) - sizeof(char[14]));

    The GCC and Clang extensions normalize the undefined behavior when performing an out-of-bounds access on an array. The program performs regular memory access as if it allocated the memory.

    Limitations of sized arrays

    The ability to consider sized arrays as FAM impacts the accuracy of some kinds of code analysis. Consider, for instance, the -fsanitize=bounds option in which the instruments array detects when they are out-of-bounds. Without any context information, it cannot add a check to the following access:

    struct fam {
    
       int size;
    
       double data[];
    
    };
    
    int foo(struct fam* f) {  return f -> data[8]; }

    But if we declare the array as double data[1], there is still no instrumentation. The compiler detects a FAM based on the extension definition and performs no check. Even worse, if we declare the array as double data[4], trunk GCC performs no check (honoring legacy code, as illustrated in the previous section), while Clang adds a bounds check.

    We observe the same behavior for the __builtin_object_size builtin. This builtin computes the allocated memory reachable from a pointer. When asked for __builtin_object_size(f - > data, 1), both GCC and Clang return -1 (indicating a failure to compute that size) for all the declarations of data we have explored so far. This policy is conservative and removes some of the security offered by _FORTIFY_SOURCE, which relies heavily on the accuracy of __builtin_object_size.

    Motivation for stricter standard conformance

    A codebase that strictly conforms to the C99 standard (at least for FAM) would benefit from a compiler strictly following the standard definition of flexible array members. That goal motivates an effort currently led within the Linux kernel community, as demonstrated by this patch. The documentation update favors C99 FAM in place of zero-length arrays.

    To take advantage of this development, they developed a compiler option using GCC and Clang to give the programmer control over flexible array syntax. The option is -fstrict-flex-arrays= whereas:

    • 0 reflects the current situation described earlier.
    • 1 considers only [0], [1] and [ ] as a FAM.
    • 2 considers only [0] and [ ]as a FAM.

    Compiling code with a -fstrict-flex-arrays value greater than 0 unlocks some extra security while breaking (some) backward compatibility, which is why n=0 remains the default.

    Compiler convergence on C-language flexible array members

    Flexible array members is an interesting C99 feature that found its way, through compiler extensions, into C89 and C++. These extensions and legacy codes led to suboptimal code checks in the compiler, which the -fstrict-flex-arrays= option can now control.

    Last updated: August 14, 2023

    Related Posts

    • How C array sizes become part of the binary interface of a library

    • Detecting memory management bugs with GCC 11, Part 1: Understanding dynamic allocation

    • Customize the compilation process with Clang: Optimization options

    • How data layout affects memory performance

    Recent Posts

    • Introducing Red Hat build of Cryostat 4.0

    • How we improved AI inference on macOS Podman containers

    • How OpenShift Virtualization supports VM live migration

    • How SELinux deny rules improve system security

    • Advanced time manipulation with GDB

    What’s up next?

    Getting GitOps e-book card

    Learn how to navigate the complex world of modern container-based software development and distribution with Getting GitOps: A Practical Platform with OpenShift, Argo CD, and Tekton.

    Get the e-book
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue