Search code examples
cmemoryallocationvariable-length-array

When to use Variable Length Array (VLA)?


  • malloc is slow and allocates on the heap. Good for large objects or objects that need to get their lifetime extended beyond the function where they are created.
  • static allocation is on the stack. Allocation baked in by compiler so essentially free time-wise. Good for small objects. Risk of SO otherwise.

In a nutshell, I stand by these rules to decide how to allocate blocks of memory.

I work on embedded devices where time and space constraints are exacerbated, and I cringe whenever I see VLA as I don't know what the underlying implementation will do and whether it will make the right choice. So my rule of thumb is to stay away from them. Are there situations where it is preferable to use VLA rather than the classical malloc or static allocations, especially with respect to the embedded space?


Solution

  • I cannot think of a good use of VLAs in embedded space. I'm hard pressed to think of a good use in applications space.

    I have used them in the past as working storage when tokenizing or manipulating strings:

    void tokenize( const char *str )
    {
      /**
       * Copy input string to temporary buffer and tokenize
       * that buffer, leaving the original string unmolested
       */
      char tmp[strlen( str )+1];
      strcpy( tmp, str );
      char *tok = strtok( tmp, " " );
      while ( tok )
      {
        // do something interesting with the token
        tok = strtok( NULL, " " );
      }
    }
    

    But it's not something I've done all that often.