Migrating to C18 with Optional VLA Support: Uncertain Runtime Impact
0 reputation · 06 Aug 2020, 17:33 UTC
0 reputation · 06 Aug 2020, 17:33 UTC
We plan to upgrade a small C application that relies on Variable Length Arrays (VLAs) to C18 while keeping the service running.
In C18 (C11), VLA support is optional; many compilers still provide it as an extension, but some omit it entirely. If a compiler silently removes VLA support, the program may allocate stack memory incorrectly, leading to overflows or crashes.
We need to determine whether the target compiler will handle VLAs at runtime, and if refactoring VLAs to dynamic allocations will preserve the original stack‑usage profile required by the real‑time constraints.
34775 reputation · 06 Aug 2020, 20:55 UTC
In C18 a compiler that does not support VLAs will reject VLA declarations with a compile‑time error; it does not silently treat them as fixed‑size arrays.
__STDC_NO_VLA__. If the macro is defined, the compiler lacks VLA support; if it is undefined, VLAs are supported.malloc/free moves the allocation from the stack to the heap, reducing peak stack usage but adding heap consumption, allocation overhead, and potential fragmentation.clang-analyze) or runtime instrumentation (e.g., debugger stack‑pointer sampling), and heap usage with a profiler such as Valgrind Massif.When a C18 compiler omits VLA support, the language treats the VLA syntax as a constraint violation, triggering a diagnostic. The macro __STDC_NO_VLA__ is the standard, portable way to query this capability without leaving C11 mode.
-std=c18 and inspect __STDC_NO_VLA__:
#include <stdio.h>
int main(void) {
#ifdef __STDC_NO_VLA__
puts("VLA not supported");
#else
puts("VLA supported");
#endif
return 0;
}
type var[N];) to dynamic allocation:
type *var = malloc(N * sizeof *var);
if (!var) { /* handle error */ }
/* use var */
free(var);
To decide whether the heap overhead is acceptable, we need to know the maximum allowable stack size (or stack budget) for the real‑time task. If the stack budget is tight, the reduction from removing VLAs may be essential; otherwise, the heap overhead could be the limiting factor.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.