C++内存分配方法
#include <iostream>
#include <cstring> // or string.h
using namespace std;
char * getname(void); // function prototype
int main()
{
char * name; // create pointer but no storage
name = getname(); // assign address of string to name
cout << name << " at " << (int *) name << "\n";
delete [] name; // memory freed
name = getname(); // reuse freed memory
cout << name << " at " << (int *) name << "\n";
delete [] name; // memory freed again
// cin.get();
// cin.get();
return 0;
}
char * getname() // return pointer to new string
{
char temp[80]; // temporary storage
cout << "Enter last name: ";
cin >> temp;
char * pn = new char[strlen(temp) + 1];
strcpy(pn, temp); // copy string into smaller space
return pn; // temp lost when function ends
}
自动存储
函数内部定义的常规变量使用自动存储空间,被称为自动变量。
通俗的来说自动变量就是常说的局部变量,作用域在包含它的代码块,当函数调用结束后,该变量就会被释放,参考上面代码getname()里的 temp数组。
自动变量通常存储在栈区,变量遵循一种后进先出的原则,后定义的先释放。
静态存储
stastic double fee = 56.50;
变量可以存在于整个声明周期,在函数调用结束后不会被释放。
动态存储
通过new和delete运算符提供的一种灵活的存储方式。在C++种称为自由存储空间或叫做堆,数据的生命周期不完全受程序或函数的生存时间控制。new和delete必须配套使用,防止在大型项目开发中造成内存泄漏的现象。