且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

VLA大量溢出

更新时间:2023-11-10 14:58:40

int (*a)[n];不是VLA,而是指向VLA的指针.因此,OP 2示例还不够接近.

int (*a)[n]; is not a VLA, but a pointer to a VLA. So OP 2 examples are not a close enough comparison.

@MM 所述,防止堆栈溢出是任何问题自动分配.递归会过度消耗堆栈.局部大变量也可能过度消耗堆栈.

As @M.M commented, preventing stack overflow is a problem with any automatic allocation. Recursion can overly consume a stack. Local large variables can overly consume a stack too.

VLA只是更可能被严重使用的一种.

A VLA is simply one of the more likely to be used egregiously.

// Qualified use of VLA
int len = snprintf(NULL, 0 "%d", some_int);
assert(len > 0);
char vla_good[len+1];
len = snprintf(vla_good, len+1, "%d", some_int);

// Unqualified
int x;
scanf("%d", &x);
char vla_bad[x];  // who knowns what x may be, did scanf() even work?


VLA引入的问题超出了其解决的范围,因为您永远不知道对于x对于堆栈而言太大而言,声明是否会崩溃.

VLAs introduce more problems than they solve, because you never know if the declaration is going to crash for x being too large for the stack.

我们可以确定使用VLA是否危险?

Can we determine if the use of a VLA is dangerous?

使用正确的工具完成任务.通常,最坏的情况是使用小型固定大小的阵列. VLA用途有限.健壮的代码可以确保在声明VLA之前,数组元素的数量不会是愚蠢的.

Use the right tool for the task. Usually a worst-case small fixed-sized arrays will do. VLAs have limited uses. Robust code would insure the array element count is not foolish before declaring a VLA.

请注意,C11可选地支持VLA(自C99开始可用).

Note that VLA, available since C99 is optionally supported in C11.

VLA不错,它们是那样.

VLA are not bad, they are just drawn that way.