☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

避免使用变长数组

2.19 ID_variableLengthArray
目录 › next › previous

使用变长数组(variable length array)可以在栈上动态分配内存,但分配失败时难以通过标准方法控制程序的行为。

变长数组由 C99 标准提出,不在 C++ 标准之内,在 C++ 代码中不应使用。

示例:

void foo(int n)
{
    int a[n];   // Non-compliant, a variable length array
                // Undefined behavior if n <= 0
    ....
}

例中数组 a 的长度为变量,其内存空间在运行时动态分配,如果 n 不是合理的正整数会导致未定义的行为。

另外,对于本应兼容的数组类型,如果长度不同也会导致未定义的行为,如:

void bar(int n)
{
    int a[5];
    typedef int t[n];   // Non-compliant, a variable length array type
    t* p = &a;          // Undefined behavior if n != 5
    ....
}

相关

ID_stackAllocation

依据

ISO/IEC 9899:1999 6.7.5.2(5) ISO/IEC 9899:2011 6.7.6.2(5)

参考

MISRA C 2012 18.8
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.