在此处发布我的代码片段。我正试图在调试中立足。

struct dirent *s_dirent;
char path[300];
....
bzero(path,300);
...
fd_dir = opendir(path);
while((s_dirent = readdir(fd_dir))!=NULL)
{
     if(s_dirent->d_name[0] == '.')
          continue;
     else
          break;
 }
if(s_dirent == NULL)
{
   if(closedir(fd_dir)!=0)
       perror("Error on closedir");
 }
else
{

  if(closedir(fd_dir)!=0)/*Line number 249*/
      perror("Error on closedir");

  /*some comments*/
  strcat(path,"/");
  strcat(path,s_dirent->d_name);/*Line number 254*/
 }

Valgrind 输出:
==3287== Invalid read of size 1
==3287==    at 0x40069E0: strcat (mc_replace_strmem.c:176)
==3287==    by 0x804D6B4: online_bck (backup_manager.c:254)
==3287==    by 0x8049F96: on_bck_beg (TxFS_manager.c:181)
==3287==    by 0x8049818: handler (Reader.c:236)
==3287==    by 0xBF5F18: start_thread (in /lib/libpthread-2.12.90.so)
==3287==    by 0xB37A2D: clone (in /lib/libc-2.12.90.so)
==3287==  Address 0x402a39b is 35 bytes inside a block of size 32,792 free'd
==3287==    at 0x40057F6: free (vg_replace_malloc.c:325)
==3287==    by 0xAF6C67: closedir (in /lib/libc-2.12.90.so)
==3287==    by 0x804D65A: online_bck (backup_manager.c:249)
==3287==    by 0x8049F96: on_bck_beg (TxFS_manager.c:181)
==3287==    by 0x8049818: handler (Reader.c:236)
==3287==    by 0xBF5F18: start_thread (in /lib/libpthread-2.12.90.so)
==3287==    by 0xB37A2D: clone (in /lib/libc-2.12.90.so)

任何帮助将不胜感激。
谢谢

最佳答案

您不应访问在调用 readdir() 后由 closedir() 返回的数据。这是因为 closedir() 可能会释放在 opendir/readdir 中分配的任何资源(例如内存)。

如果你想保存 dirent* 结构,你可以切换到 readdir 的 readdir_r 变体(使用不同的参数集)。

更新:Valgrind 输出的解码:

        V - note single space here; it is beginning of error message.
==3287== Invalid read of size 1
==3287==    at 0x40069E0: strcat (mc_replace_strmem.c:176)

 backtrace skipped

Valgrind 说错误是 Reading of invalid data, sized 1 byte ,这不是内存泄漏。这是不正确的内存访问。而这次读取的参与者是 strcat()(由跳过的回溯调用)。为什么数据无效?有子消息
        VV - note two spaces here, it is continuation of error message
==3287==  Address 0x402a39b is 35 bytes inside a block of size 32,792 free'd
==3287==    at 0x40057F6: free (vg_replace_malloc.c:325)
==3287==    by 0xAF6C67: closedir (in /lib/libc-2.12.90.so)

该字节无效(不允许从中读取),因为它是 free-d 内存段的一部分(您无法从刚刚 free-d 的内存中读取)。这是谁做的?查看回溯:closedir 是 free 的调用者。

关于c - Readdir/closedir - Valgrind 显示 "invalid read",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6964319/

10-15 22:22