7

As I understand it, when we define an array like const char argv[SIZE]; "SIZE" must be a number which is known at compile time.

But recently I read AOSP code, and found this: http://androidxref.com/5.1.1_r6/xref/system/netd/server/NetdConstants.cpp#70

static int execIptables(IptablesTarget target, bool silent, va_list args) {
    /* Read arguments from incoming va_list; we expect the list to be NULL terminated. */
    std::list<const char*> argsList;
    argsList.push_back(NULL);
    const char* arg;
    do {
        arg = va_arg(args, const char *);
        argsList.push_back(arg);
    } while (arg);

    int i = 0;
    const char* argv[argsList.size()];
    ...

It seems that const char* argv[argsList.size()]; uses a size which is only known at runtime. Is this because this array is defined in a function which will allocate the array in the stack or because the compiler can figure out what the size is at compile time?

7
  • Some compilers support (as an extension) arrays on the stack with a size that is only known at runtime. Commented Feb 15, 2017 at 8:18
  • 1
    The author is expecting a non-standard feature (variable length arrays, VLAs) to be supported by whatever C++ compiler is building this code. Commented Feb 15, 2017 at 8:19
  • 3
    An std::list used to accumulate varargs then used to create a VLA and copy everything there? Who the hell wrote this garbage? I don't want to use this phone anymore... Commented Feb 15, 2017 at 8:20
  • 4
    @MatteoItalia Concur. I would have just used std::vector<const char*> and thrown out both the std::list and the VLA. Commented Feb 15, 2017 at 8:21
  • relevant: stackoverflow.com/questions/8593643/… Commented Feb 15, 2017 at 8:30

1 Answer 1

0

The correct terminology is variable-length-array (VLA).

The C++ language standard does not support this feature.

The C language standard started supporting it at some point.

Allocation in memory is compiler-dependent (i.e., not dictated by the standard).

Sign up to request clarification or add additional context in comments.

5 Comments

You should specify that, even if standard C++ doesn't support it, it's a common extension (supported by both gcc and clang).
@MatteoItalia: OK, good point. I was referring to the general standard of course. Your comment here will do this for me (since I'm not sure what other C++ compilers support this). Thank you :)
Gcc and clang, but not MSVC - which could be an issue depending on your target platforms.
@MartinBonner: I don't have specific information on every compiler out there (let alone, on every future compiler). That's why I preferred to keep this answer platform-agnostic. Anyone making use of it, should check their specific compiler.
Yes. My preference is to avoid using extensions (except things which add extra compiler warnings like __attribute__(format(printf)), and which can be hidden behind #ifdef's). Particularly when there's a perfectly good equivalent in C++ already: std::vector.