本文介绍了VLA大量溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于其他线程中某人的评论:

Based on a comment of someone in another thread:

此代码将溢出,因为sizeof(a)对于堆栈而言太长了:

This code will overflow because sizeof(a) is too long for the stack:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n = 100000000;
    int a[4][n];

    printf("%zu\n", sizeof(a));

    return 0;
}

但这不能是因为sizeof(a)是8(计算机中指针的大小):

But this one can not because sizeof(a) is 8 (the size of a pointer in my computer):

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n = 100000000;
    int (*a)[n];

    printf("%zu\n", sizeof(a));
    a = malloc(sizeof(*a) * 4);
    free(a);
    return 0;
}

我的假设正确吗?

我们可以根据sizeof对象确定使用VLA是否危险(可能溢出)?

Can we determine if the use of a VLA is dangerous or not (may overflow) based on the sizeof the object?

推荐答案

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是否危险?

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.

这篇关于VLA大量溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:27