内存泄漏问题

8
我有一个简单的程序,它创建了一个线程,并等待这个线程结束,然后程序也结束。当我使用C(gcc)编译器编译这个程序,并用valgrind检查时,没有出现任何问题,但是当我使用C++(g ++)编译器编译并用valgrind检查时,它显示我的程序存在内存泄漏。可能的问题是什么?
下面是我的程序:
#include <pthread.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>


unsigned char b = 0;


void* threadfunc1( void *pVoid )
{
    while( b == 0 )
    {
    usleep(10000);
    }
    pthread_exit(0);
}



int main(void)
{

    int status;
    pthread_attr_t tattr;
    pthread_t   thread1;

    status = pthread_attr_init(&tattr);
    status = pthread_attr_setdetachstate(&tattr,PTHREAD_CREATE_JOINABLE);
    status = pthread_attr_setscope(&tattr,PTHREAD_SCOPE_SYSTEM);

    if( pthread_create( &thread1, &tattr, threadfunc1, NULL ) != 0 )
    {
        exit(1);
    }

    usleep(1000000);
    b = 1;
    pthread_join( thread1, NULL);
    usleep(2000000);

    return 0;
}

这是我使用g++编译并在valgrind中检查后得到的结果。
==7658== HEAP SUMMARY:
==7658==     in use at exit: 28 bytes in 1 blocks
==7658==   total heap usage: 2 allocs, 1 frees, 172 bytes allocated
==7658== 
==7658== 28 bytes in 1 blocks are still reachable in loss record 1 of 1
==7658==    at 0x4024C1C: malloc (vg_replace_malloc.c:195)
==7658==    by 0x400C01E: _dl_map_object_deps (dl-deps.c:506)
==7658==    by 0x40117E0: dl_open_worker (dl-open.c:297)
==7658==    by 0x400D485: _dl_catch_error (dl-error.c:178)
==7658==    by 0x401119F: _dl_open (dl-open.c:586)
==7658==    by 0x428D0C1: do_dlopen (dl-libc.c:86)
==7658==    by 0x400D485: _dl_catch_error (dl-error.c:178)
==7658==    by 0x428D1C0: dlerror_run (dl-libc.c:47)
==7658==    by 0x428D2DA: __libc_dlopen_mode (dl-libc.c:160)
==7658==    by 0x4048876: pthread_cancel_init (unwind-forcedunwind.c:53)
==7658==    by 0x40489EC: _Unwind_ForcedUnwind (unwind-forcedunwind.c:126)
==7658==    by 0x40464B7: __pthread_unwind (unwind.c:130)
==7658== 
==7658== LEAK SUMMARY:
==7658==    definitely lost: 0 bytes in 0 blocks
==7658==    indirectly lost: 0 bytes in 0 blocks
==7658==      possibly lost: 0 bytes in 0 blocks
==7658==    still reachable: 28 bytes in 1 blocks
==7658==         suppressed: 0 bytes in 0 blocks

所以,我做错了什么,是我的错误还是...,为什么当我使用gcc编译时没有问题,但当我使用C++编译时存在内存泄漏?

编写多语言源文件很困难。预计会有更多的问题。我建议你只使用C或C++中的一种。 - pmg
我从朋友那里得到了这个程序,他通过makefile编译它,但是我在NetBeans中为此程序创建了新项目,由于我的默认编译器是gcc,所以在编译和运行时没有任何问题,但是当我通过makefile编译它时,就会出现内存泄漏的问题,因此很有意思想知道为什么会出现这种情况? - akmal
2个回答

7

正如@Kiril Kirov的答案所指出的那样,你的程序中没有内存泄漏。

但我没有看到调用:

int pthread_attr_destroy(pthread_attr_t *attr); 

关于 pthread_attr_destroy 函数,我在编辑这个问题时似乎不小心删除了它。谢谢你的回答! - akmal
1
@akmal:这就解释了为什么即使调用缺失也不会显示泄漏 :) - Alok Save

6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接