Large VLA overflow

瘦欲@ 提交于 2019-11-28 14:02:36
chux

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


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.

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?

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.

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

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!