作者:爱吃肉肉的狼 | 来源:互联网 | 2023-09-18 17:26
在此处发布我的代码段.我正在尝试调试.structdirent*s_dirent;charpath[300];.bzero(path,300);fd_diropendi
在此处发布我的代码段.我正在尝试调试.
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)
任何帮助将不胜感激.
谢谢
解决方法:
调用closedir()后,您不应访问由readdir()返回的数据.这是因为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说错误是读取无效数据,大小为1字节,这不是内存泄漏.这是错误的内存访问.读取的参与者是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(您无法从刚刚释放的内存中读取).是谁做的看回溯:closedir是free的调用者.