c++ - 分配受控内存 - 数组大小(以字节为单位)

标签 c++ memory allocation

我想学习如何处理内存分配和取消分配。我的第一个“任务”是体验一下。

基本上,我想使用 new 运算符分配 1 kB 内存,直到抛出异常。我不太确定如何执行此操作,但我希望它与此类似:

int main(){
unsigned int counter = 0;
try{
    for (int i = 0; i < 10; i++){
            int *p_array = new int[1024*i];
            cout << sizeof(p_array);
            counter++
        }
    delete[] p_array; 
}catch (std::bad_alloc& ba){
    std::cerr << "bad_alloc caught: " << ba.what() << endl << "Allocated 1KB " << counter << " times";
}
return 0;
}

错误:

test.cpp: In function ‘int main()’:
test.cpp:24:12: error: ‘p_array’ was not declared in this scope
make: *** [out_Executable] Error 1

非常简单的程序,但我仍然卡住了。有人可以帮帮我吗?

最佳答案

你有一些形式(简化)

{
  int * p = ...; // p only exists in this scope
}
delete p; // p doesn't exist here

您正在声明一个 int* 并为循环的每次迭代分配一个数组。 int* 仅在单次迭代期间存在。不过,数组本身会一直存在到程序结束。

关于c++ - 分配受控内存 - 数组大小(以字节为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15260065/

相关文章:

algorithm - 递归函数和使用堆栈在内存使用方面的区别

c - 解码这些 Valgrind 调试器内存错误在我的代码中意味着什么

c - 为什么这段代码不在 C 中分配内存?

c++ - 如何预分配(保留)priority_queue<vector>?

c++ - 链接到旧版本 g++ 编译的动态库时,我应该注意什么潜在问题吗?

c++将函数作为参数传递给另一个带有void指针的函数

performance - 大型 portlet war 占用内存导致性能问题?

c# - 读取和写入内存地址以验证不安全代码中的内存分配

c++ - 派生结构与指向其他结构的结构

c++ - 使用 Boost::Spirit::X3 解析复数