内存安全程序设计
2025年4月23日大约 2 分钟
Background
Pointer
A pointer is a varaible that contains the memory address of a portion of memory, that is , pointer holds address
- Dereferencing operator: *p refers to the object pointed to by the pointer.
- Address operator: get the address of an object.
- The size of pointer is fixed, it depends on your computer. (64位的机器的指针有8个字节)
Dynamic and local pointer
注意用new申请的内存要用delete删除,用new申请的内存在heap上;
int *p1,*p2, n;
//p1 p2 n are variables in the stack
p1= new int;
// allocate memory in the heap
*p1= 10;
p2= p1;
//p1 and p2 points to the same memory
Memory-safety Problems
Use after free
指针释放之后继续使用,导致异常
Buffer overflow
访问非法的空间
Doule free
重复释放指针
记得: 在delete之后将指针赋值为null,在new一个新的pointer之前确定原先的指针指向的内容已经被删除或者还有其他指针占用。new后一定要delete!
Memory-safety Programming
Tempora Memory Problems
时间类的内存问题,use after free, memory leak, double free
Danglnig Pointer比如:
int main(){
int* ptr;
{
//create an inner block;
int a=1;
ptr=&a;
}
cout<<*ptr; // Dangling pointer;
}
In this case, a is a temporary varible in the block;
Then, how to exscape such problems ???
什么是RAII
如果文件打开但是忘记close可能会带来一些问题,我们可以用过RAII的思想,来封装一个类来解决这个问题。
Resource Acquisition Is Initialisation (Constructor Aquires , Destructor Releases)
class FileObj{
public:
File* ptr;
Fileobj(char* name){
//打开文件
}
~Fileobj(){
//close the file when deconstructings
}
}
void printFile(const char* name){
Fileobj file(name);
//这个是local地创建,创建在stack上,而非在heap上创建,确保会自动回收;
}
int main(){
FileObj file1("file1");
//local地创建file而非用new创建,保证会自动地调用deconstructor
}
基于RAII的思想(Resources accusition is initialized )我们可以设计smart pointer;
smartPointer核心背后的逻辑;