使用OpenMP进行编译会导致内存泄漏

时间:2014-10-15 20:19:38

标签: c gcc memory-leaks openmp

根据valgrind的说法,在使用OpenMP编译一个简单的hello-world程序时,我可能会导致内存泄漏。这没有意义,因为hello-world程序不会故意使用任何OpenMP功能。

假设下面的程序名为hi.c并根据

编译

$ gcc -o hi hi.c

GCC版本4.8.3

#include <stdio.h>

int main( void )
{
  printf( "hi\n" );
  return 1;
}

我们应该期待来自valgrind的泄漏报告来验证显而易见的:没有泄漏。我的观察结果与此假设一致:

$ valgrind --tool=memcheck ./hi
==13064== Memcheck, a memory error detector
==13064== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==13064== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info
==13064== Command: ./hi
==13064== 
hi
==13064== 
==13064== HEAP SUMMARY:
==13064==     in use at exit: 0 bytes in 0 blocks
==13064==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==13064== 
==13064== All heap blocks were freed -- no leaks are possible
==13064== 
==13064== For counts of detected and suppressed errors, rerun with: -v
==13064== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

我还希望在使用其他标志编译后收到相同的报告。然而,这种情况并非如此。当我使用-fopenmp标志进行编译时,我发现内存泄漏

$ gcc -fopenmp -o hi hi.c

$ valgrind --tool=memcheck ./hi
==13084== Memcheck, a memory error detector
==13084== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==13084== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info
==13084== Command: ./hi
==13084== 
hi
==13084== 
==13084== HEAP SUMMARY:
==13084==     in use at exit: 8 bytes in 1 blocks
==13084==   total heap usage: 2 allocs, 1 frees, 32,824 bytes allocated
==13084== 
==13084== LEAK SUMMARY:
==13084==    definitely lost: 0 bytes in 0 blocks
==13084==    indirectly lost: 0 bytes in 0 blocks
==13084==      possibly lost: 0 bytes in 0 blocks
==13084==    still reachable: 8 bytes in 1 blocks
==13084==         suppressed: 0 bytes in 0 blocks
==13084== Rerun with --leak-check=full to see details of leaked memory
==13084== 
==13084== For counts of detected and suppressed errors, rerun with: -v
==13084== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

有没有人理解为什么使用OpenMP进行编译会导致内存泄漏?虽然这个特定的程序没有调用OpenMP,但我想确保在最终使用它时正确处理内存。

1 个答案:

答案 0 :(得分:1)

valgrind报告没有描述内存泄漏。在程序出口处剩余分配的堆内存仍然可以访问。

您的编译器的openmp实现很可能会在程序中注入一个全局变量,并使其在程序启动时(即main()之前)动态分配。