我想学习如何处理内存分配和取消分配。我的第一个“任务”是体验一下。
基本上,我想使用 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/