内存分配
1 栈结构分配(Frame Allocation)
栈结构用于存放调用函数传递的参数和函数中的局部变量的内存块。编译器自动为堆栈分配和回收内存空间。堆栈有一定的作用域,当程序执行离开堆栈的作用域的时候,堆栈空间自动释放。
栈结构用于存放调用函数传递的参数和函数中的局部变量的内存块。编译器自动为堆栈分配和回收内存空间。堆栈有一定的作用域,当程序执行离开堆栈的作用域的时候,堆栈空间自动释放。
2 堆内内存分配
堆是为了程序运行保留的内存块,它是在程序代码(code)和堆栈(stack)之外的内存块。标准的C语言用molloc函数和free函数在堆内分配和释放内存块;MFC程序提供了内嵌的操作符new和delete在堆上分配和释放内存。
堆是为了程序运行保留的内存块,它是在程序代码(code)和堆栈(stack)之外的内存块。标准的C语言用molloc函数和free函数在堆内分配和释放内存块;MFC程序提供了内嵌的操作符new和delete在堆上分配和释放内存。
3 两种形式的内存分配例子
(1) 数组的分配
如果是如下方式定义的数组,则会在栈上分配内存空间,离开作用域以后会自动被删除;
{
const int nBuffer_Size = 128;
// Allocation on the frame
char chMyCharArray[nBuffer_Size];
int nMyIntArray[nBuffer_Size];
...
// Reclaimed when exiting scope
如果是如下方式定义的数组,则会在栈上分配内存空间,离开作用域以后会自动被删除;
{
const int nBuffer_Size = 128;
// Allocation on the frame
char chMyCharArray[nBuffer_Size];
int nMyIntArray[nBuffer_Size];
...
// Reclaimed when exiting scope
使用new操作符在堆上分配内存:
const int nBufferSize = 128;
// Allocation on the heap
char* chMyCharArray = new char[nBufferSize];
int* nMyIntArray = new int[nBufferSize];
删除堆内的数组的时候用delete操作符。
delete[] chMyCharArray;
delete[] nMyIntArray;
const int nBufferSize = 128;
// Allocation on the heap
char* chMyCharArray = new char[nBufferSize];
int* nMyIntArray = new int[nBufferSize];
删除堆内的数组的时候用delete操作符。
delete[] chMyCharArray;
delete[] nMyIntArray;
(2) 为结构体分配内存
如果是如下方式定义和使用的话,在栈上分配内存
struct MyStruct_t { int nTopScore; };
void SomeFunction(void)
{
// Allocation on frame
MyStruct_t myScore;
// Use the struct
myScore.nTopScore = 90;
{
// Allocation on frame
MyStruct_t myScore;
// Use the struct
myScore.nTopScore = 90;
...
// Relaimed when exiting scope
}
// Relaimed when exiting scope
}
使用new操作符在堆内为结构体分配内存
// heap allocation
MyStruct_t* myStuct = new MyStruct_t;
// heap allocation
MyStruct_t* myStuct = new MyStruct_t;
// Use the struct
myStruct->nTopScore = 90;
myStruct->nTopScore = 90;
...
delete myStruct;
delete myStruct;
(3) 为对象分配空间
在栈上为对象分配地址空间;
声明的对象如下:
{
// Allocation on frame
CPerson myPerson;
声明的对象如下:
{
// Allocation on frame
CPerson myPerson;
// Use the object
myPerson.SomeMemberFunction();
myPerson.SomeMemberFunction();
}
对象的析构函数在超出作用域范围时自动被调用。
对象的析构函数在超出作用域范围时自动被调用。
使用new操作符在堆上分配内存空间:
// Allocation on heap
CPerson* myPerson = new CPerson;
CPerson* myPerson = new CPerson;
// Use the object
myPerson->SomeMemberFunction();
myPerson->SomeMemberFunction();
delete myPerson;
3361

被折叠的 条评论
为什么被折叠?



