【问题标题】:Static vs Dynamic Memory allocation of an array数组的静态与动态内存分配
【发布时间】:2021-04-01 02:45:36
【问题描述】:

在运行时使用“new”关键字进行动态内存分配和使用以下方法之间声明数组的大小和使用以下方法之间哪个更节省内存以及为什么:

#include <iostream>

using namespace std;

int main ()
{
    int size;

    cin >> size;

    int a[size];
}

使用“新”关键字进行动态内存分配

#include <iostream>

using namespace std;

int main ()
{
    int *array {nullptr};
    
    int size;

    cin >> size;

    array = new int[size];
     
    delete [] array;
}

【问题讨论】:

  • int a[size]; 不是有效的 C++(使用 VLA 扩展)。
  • 为什么 ```int a[size]`` 无效并且编译没有错误?
  • int a[size]; 无法在 MSVC 上编译:godbolt.org/z/xo13cW - 如前所述,它不是标准 C++,它使用一些编译器支持的扩展
  • 这能回答你的问题吗? c++ dynamic memory allocation using "new"
  • 第二个 sn-p 有内存泄漏。更喜欢 std::vector 而不是原始拥有指针。

标签: c++ pointers memory-management dynamic-memory-allocation member-function-pointers


【解决方案1】:

两者各有利弊,取决于您想要达到的目标。当在堆栈上分配时,编译器会自动完成内存分配和释放,而在堆上你必须在堆上分配和专用内存你可以根据你的要求重新定位和调整所需的内存大小,这在堆栈上是不可能的。

【讨论】:

    【解决方案2】:

    在堆栈上分配内存要快得多(主要是通过更改堆栈指针)。而且您不必担心管理它,它会在函数退出时被释放。但是堆栈大小通常比堆大小小得多。对于小的本地对象,使用堆栈,对于大的和那些生命周期超出函数范围的对象 - 堆。

    【讨论】:

    • 在 OP 的代码 sn-p 的上下文中,使用 VLA 扩展既不可移植也很危险,因为大小受用户输入的影响(生成堆栈溢出和引入漏洞的简单方法)。可能值得一提
    猜你喜欢
    • 2016-02-01
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 2013-11-10
    • 2014-10-12
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多