Valgrind检查C语言中的内存泄漏问题。

3
我们在C语言中编写了一套代码,可以将Matlab数据文件(.mat)作为输入,并调用GSL函数来搜索多项式的根和生成随机数。我们正在使用OSX操作系统。我们使用Valgrind来检查是否存在内存泄漏,因为我们在代码中使用了相当多的malloc和free。确实帮助我们在许多地方找到了内存泄漏问题。然而,仍有一个问题无法解决。该问题存在于名为maxphaseutils.c的子例程中的listfileswext函数中(它列出具有给定扩展名即.mat的目录中的所有文件)。
char ** listfileswext (const char *ext, const char *dirName, size_t *nFiles, size_t *maxFileNameLen)
{
    /*printf("------- %s -------\n",ext);
    printf("Extension string length %zu\n",strlen(ext));*/
  char *pattern = (char *)malloc((3+strlen(ext))*sizeof(char));
  DIR *dp;
  struct dirent *ep;
  char **fileList;
  size_t lpc;

  pattern[0] = '*';
  pattern[1] = '.';
  pattern[2] = '\0';
  strcat(pattern,ext);

  /*printf("Pattern %s\n",pattern);*/
  /* Step 1: Count the number of files with the required 
     extension.
  */
  size_t countValidFiles = 0;
  dp = opendir(dirName);
  if (dp != NULL){
      while ((ep = readdir(dp))){
            /*printf("Checking file %s\n",ep->d_name);*/
            if(!fnmatch(pattern, ep->d_name, (FNM_FILE_NAME|FNM_PERIOD))){
                /* Match. Increment counter */
                /*printf("found match with pattern %s\n",pattern);*/
                countValidFiles++;
            }
      }
      (void) closedir (dp);
      /*
        Apparently, there is no need to free ep as it is declared to be 'static' in the readdir function
      */
  }
  else{
    printf ("Couldn't open the directory %s\n",dirName);
    free(pattern);
    return NULL;
  }
  *nFiles = countValidFiles;
  /* Step 2: Create storage for list of filenames */
  fileList = (char **)malloc(countValidFiles*sizeof(char *));
  /* Can't find a better way than to repeat the whole loop again */
  countValidFiles = 0;
  dp = opendir(dirName);
  if (dp != NULL){
      while ((ep = readdir(dp))){
            if(!fnmatch(pattern, ep->d_name, (FNM_FILE_NAME|FNM_PERIOD))){
                fileList[countValidFiles] = (char *)malloc(strlen(ep->d_name)*sizeof(char));
                strcpy(fileList[countValidFiles],ep->d_name);
                /* Match. Increment counter */
                countValidFiles++;
            }
      }
      (void) closedir (dp);
  }
  else{
    printf ("Couldn't open the directory %s\n",dirName);
    return NULL;
  }

    /*Find longest filename */
    size_t fileNameLen;
    *maxFileNameLen = 0;
    size_t lpc1;
    for (lpc1 = 0; lpc1 < *nFiles; lpc1++){
        fileNameLen = strlen(fileList[lpc1]);
        if ( fileNameLen > *maxFileNameLen)
            *maxFileNameLen = fileNameLen;
    }

  /* Wrap up */
  free(pattern);
  return fileList;
}   

在这个函数中,变量fileList被调用。
char **inputFileList;
    size_t nInputFiles, maxFileNameLen;
    inputFileList = listfileswext("mat", simDataDir, &nInputFiles, &maxFileNameLen);

然后释放

for(lpc1 = 0; lpc1 < nInputFiles; lpc1++){
        /* Free up dynamically allocated memory for file list*/
        free(inputFileList[lpc1]);
    }
    /* Free up dynamically allocated memory */
free(inputFileList);

如上所示,在主函数中。您可以看到fileList在主函数中被释放为inputFileList,而不是在分配的函数(listfileswext)中释放。我们认为这是可以的。运行Valgrind后,它显示

==8643== Invalid write of size 8
==8643==    at 0x101921031: _platform_memmove$VARIANT$Unknown (in /usr/lib/system/libsystem_platform.dylib)
==8643==    by 0x1016E33AD: stpcpy (in /usr/lib/system/libsystem_c.dylib)
==8643==    by 0x101755F96: __strcpy_chk (in /usr/lib/system/libsystem_c.dylib)
==8643==    by 0x1000044B2: listfileswext (maxphaseutils.c:153)
==8643==    by 0x100005FBD: main (perfeval_snglproc.c:41)
==8643==  Address 0x104c6381d is 13 bytes inside a block of size 20 alloc'd
==8643==    at 0x100010EBB: malloc (vg_replace_malloc.c:303)
==8643==    by 0x10000447C: listfileswext (maxphaseutils.c:152)
==8643==    by 0x100005FBD: main (c:41)

并且

==8643== Invalid read of size 8
==8643==    at 0x101921040: _platform_memmove$VARIANT$Unknown (in /usr/lib/system/libsystem_platform.dylib)
==8643==    by 0x101756127: __strcat_chk (in /usr/lib/system/libsystem_c.dylib)
==8643==    by 0x1000060CE: main (perfeval_snglproc.c:67)
==8643==  Address 0x104c63224 is 4 bytes inside a block of size 11 alloc'd
==8643==    at 0x100010EBB: malloc (vg_replace_malloc.c:303)
==8643==    by 0x10000447C: listfileswext (maxphaseutils.c:152)
==8643==    by 0x100005FBD: main (perfeval_snglproc.c:41)

这里的主要文件是perfeval_snglproc.c。此外,还有一些与我们编写的功能似乎无关的文件(这些系统文件可能不受我们的控制):

==8643== 168 bytes in 7 blocks are possibly lost in loss record 657 of 1,081
==8643==    at 0x10001178B: malloc_zone_calloc (vg_replace_malloc.c:717)
==8643==    by 0x1019C737C: NXHashInsert (in /usr/lib/libobjc.A.dylib)
==8643==    by 0x1019C746F: _NXHashRehashToCapacity (in /usr/lib/libobjc.A.dylib)
==8643==    by 0x1019C73B9: NXHashInsert (in /usr/lib/libobjc.A.dylib)
==8643==    by 0x1019D6687: realizeClass(objc_class*) (in /usr/lib/libobjc.A.dylib)
==8643==    by 0x1019D5B53: realizeClass(objc_class*) (in /usr/lib/libobjc.A.dylib)
==8643==    by 0x1019CA38D: look_up_class (in /usr/lib/libobjc.A.dylib)
==8643==    by 0x1019CA1B9: objc_getFutureClass (in /usr/lib/libobjc.A.dylib)
==8643==    by 0x101D51D3F: __CFInitialize (in /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation)
==8643==    by 0x7FFF5FC12BC7: ImageLoaderMachO::doImageInit(ImageLoader::LinkContext const&) (in /usr/lib/dyld)
==8643==    by 0x7FFF5FC12E8C: ImageLoaderMachO::doInitialization(ImageLoader::LinkContext const&) (in /usr/lib/dyld)
==8643==    by 0x7FFF5FC0F890: ImageLoader::recursiveInitialization(ImageLoader::LinkContext const&, unsigned int, ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&) (in /usr/lib/dyld)
==8643== 
==8643== 168 (32 direct, 136 indirect) bytes in 1 blocks are definitely lost in loss record 658 of 1,081
==8643==    at 0x10001117C: malloc_zone_malloc (vg_replace_malloc.c:305)
==8643==    by 0x101D6FF79: CFUniCharGetUnicodePropertyDataForPlane (in /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation)
==8643==    by 0x101D6FEBE: CFUniCharGetNumberOfPlanesForUnicodePropertyData (in /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation)
==8643==    by 0x101D6F9A3: __CFUniCharLoadDecompositionTable (in /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation)
==8643==    by 0x101D6F048: CFUniCharDecompose (in /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation)
==8643==    by 0x101D681CE: CFStringGetFileSystemRepresentation (in /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation)
==8643==    by 0x101E91929: _CFURLCreateWithFileSystemPath (in /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation)
==8643==    by 0x101D693D9: _CFBundleCopyBundleURLForExecutableURL (in /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation)
==8643==    by 0x101D63DE4: _CFBundleGetMainBundleAlreadyLocked (in /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation)
==8643==    by 0x101D63D5A: CFBundleGetMainBundle (in /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation)
==8643==    by 0x101D8C0A7: _CFPrefsGetCacheStringForBundleID (in /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation)
==8643==    by 0x101EDADC8: __50+[CFPrefsSearchListSource withSnapshotSearchList:]_block_invoke (in /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation)

请帮忙!先行致谢!

1个回答

2

根据这个,泄漏不是由你的程序引起的,而是由系统库引起的。

对于错误,在为C字符串分配空间时,您需要留出结尾的零位,所以更改为:

 fileList[countValidFiles] = (char *)malloc(strlen(ep->d_name)*sizeof(char));

为了

 fileList[countValidFiles] = (char *)malloc((strlen(ep->d_name) + 1)*sizeof(char));

1
根据定义,sizeof(char)始终为1,因此您可以省略它们(参见C99 §6.5.3.4号3当应用于具有char、unsigned char或signed char类型(或其限定版本)的操作数时,结果为1.) - DarkDust
有一些平台上char的大小是不同的,请看这个问题 - mausik
是的,但是在CHAR_BIT > 8的平台上,sizeof(char)也会返回1。这是因为这里的大小是以字节为单位的,而CHAR_BIT定义了一个字节的大小。另请参见此问题此问题C FAQ条目。因此,在CHAR_BIT == 16的机器上,malloc(1)将分配至少16位,malloc(2)将分配至少32位... - DarkDust

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