开发者

Do I need to use delete after pthread_mutex_destroy

Suppose I use

开发者_高级运维pthread_mutex_t *m = new pthread_mutex_t;
pthread_mutex_init(m, NULL);

to initialize a mutex. Then after I'm done, and invoke pthread_mutex_destroy, do I need to use

delete m;

to release all resources?


You need to free the memory, as pthread_mutex_destroy can't do it for you.

Why doesn't pthread_mutex_destroy free the memory for you ? Because you are allowed to do this:

pthread_mutex_t m;
pthread_mutex_init(&m, NULL);

pthread_mutex_destroy(&m); /* Can't free &m. */

You can try it using valgrind:

==836== LEAK SUMMARY:
==836==    definitely lost: 24 bytes in 1 blocks


Initialization of mutex using pthread_mutex_init is different aspect; and having memory allocated for the object (of type pthread_mutex_t) is different aspect.

Using initialization routine of some library is different than allocating memory for it on heap or on stack. It is like having a FILE* as local variable, and initializing the file-pointer using fopen

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜