C语言安全编码-内存管理
Use After Free
释放内存后对其进行引用可能会导致程序崩溃,使用意外值或执行代码。
char* ptr = (char*)malloc (SIZE);if (err) {abrt = 1;free(ptr);}...if (abrt) {logError("operation aborted before commit", ptr);}
Double Free
char* ptr = (char*)malloc (SIZE);...if (abrt) {free(ptr);}...free(ptr);
Missing Release of Memory after Effective Lifetime
软件无法充分跟踪和释放使用完毕的内存,这会慢慢消耗剩余的内存。
char* getBlock(int fd) {char* buf = (char*) malloc(BLOCK_SIZE);if (!buf) {return NULL;}if (read(fd, buf, BLOCK_SIZE) != BLOCK_SIZE) {return NULL;}return buf;}
Free of Memory not on the Heap
应用程序在指向未使用关联的堆分配函数(例如malloc(),calloc()或realloc())分配的内存的指针上调用free()。
错误示例:
record_t bar[MAX_SIZE]; //Global varvoid foo(){/* do something interesting with bar */...free(bar);}
修改建议:
void foo(){record_t *bar = (record_t*)malloc(MAX_SIZE*sizeof(record_t));/* do something interesting with bar */...free(bar);}
Use of sizeof() on a Pointer Type
该代码在malloc指针类型上调用sizeof(),该指针类型始终返回字长/ 8。如果程序员打算确定已分配了多少内存,则可能会产生意外的结果。
错误代码:
double *foo;...foo = (double *)malloc(sizeof(foo));
修改建议:
double *foo;...foo = (double *)malloc(sizeof(*foo));
Uncontrolled Memory Allocation
产品基于不受信任的大小值分配内存,但是它不会验证或错误地验证了大小,从而允许分配任意数量的内存。
错误代码:
考虑下面的代码,该代码接受不受信任的大小值,并分配一个缓冲区以包含给定大小的字符串。
假设攻击者提供的大小值为:12345678
这将导致为该字符串分配305,419,896字节(超过291兆字节)。
unsigned int size = GetUntrustedInt();/* ignore integer overflow (CWE-190) for this example */unsigned int totBytes = size * sizeof(char);char *string = (char *)malloc(totBytes);InitializeString(string);
Missing Release of Resource after Effective Lifetime
在软件的有效生命期结束后,即不再需要资源后,软件不会释放资源。
错误代码:
class B;class A{public:void add_data(int index, B* data, const std::string &name);void del_data(int index);private:std::map<int,B*> m_data;std::map<int,std::string> m_name;};void A::add_data(int index, B* data, const std::string &name) {if(NULL != data) {return;}m_data[index] = data;m_name[index] = name;}void del_data(int index){free(m_data[index]);m_data.erase(index);}
valgrind
Valgrind是用于构建动态分析工具的仪器框架。有Valgrind工具可以自动检测许多内存管理和线程错误,并详细描述程序。
感兴趣的可以看看
https://www.jianshu.com/p/5a31d9aa1be2
