相关文章推荐
刚毅的花卷  ·  编程技巧 - ...·  2 年前    · 
呐喊的罐头  ·  Nginx支持WebSocket配置 - ...·  2 年前    · 
备案 控制台
学习
实践
活动
专区
工具
TVP
写文章
专栏首页 王亚昌的专栏 类静态指针的申请和释放
2 0

海报分享

类静态指针的申请和释放

如果类有一个静态成员指针变量,在进程中执行new或malloc操作分配了内存,进程退出前并不需要调用new或malloc,因为系统会自动进行释放。但这个静态成员指针变量需要多少分配,又应该如果处理呢,最近在项目代码中看到这样的例子,和大家分享一下。

#include <unistd.h>  
#include <stdio.h>  
class CPointer  
    public:  
        CPointer(){};  
        ~CPointer(){};  
    public:  
        static char * m_p;  
char * CPointer::m_p = NULL;  
void proc()  
    for(int i = 0; i < 10; i++)  
        CPointer::m_p = new char[1024*1024];  
        sleep(1);  
int main(int argc, char ** argv)  
    proc();  
    return 0;      
}  

用valgrind执行,会发现内存泄漏,如下所示,当然,这是很显然的,多次new但没有delete。

valgrind --tool=memcheck --leak-check=full  ./a.out

==3893== LEAK SUMMARY: ==3893==    definitely lost: 5,242,880 bytes in 5 blocks. ==3893==      possibly lost: 4,194,304 bytes in 4 blocks. ==3893==    still reachable: 1,048,576 bytes in 1 blocks. ==3893==         suppressed: 0 bytes in 0 blocks. ==3893== Reachable blocks (those to which a pointer was found) are not shown. ==3893== To see them, rerun with: --show-reachable=yes

那应该如何解决呢,当然是应该delete,但是类的静态成员在类的生命周期中是不能delete的,感兴趣的朋友可以试下,进程会core。

但是可以把静态指针赋给另一个局部指针,把局部指针释放掉,这样,即保存了静态指针,同时,资源也得释放。修改代码如下:

#include <unistd.h>  
#include <stdio.h>  
class CPointer  
    public:  
        CPointer(){};  
        ~CPointer(){};  
    public:  
        static char * m_p;  
char * CPointer::m_p = NULL;  
void proc()  
    for(int i = 0; i < 10; i++)  
        if (NULL != CPointer::m_p)  
            char * p = CPointer::m_p;  
            delete []p;  
            p = NULL;  
            CPointer::m_p = NULL;  
        CPointer::m_p = new char[1024*1024];  
        sleep(1);  
int main(int argc, char ** argv)  
    proc();  
    return 0;      
}  

再用valgrind执行,问题解决。

==3912== LEAK SUMMARY: ==3912==    definitely lost: 0 bytes in 0 blocks. ==3912==      possibly lost: 0 bytes in 0 blocks. ==3912==    still reachable: 1,048,576 bytes in 1 blocks.