【发布时间】:2016-06-04 15:14:02
【问题描述】:
我正在创建一个从 linux_dirent 结构 (d) 获得的文件名数组。 在循环的每次迭代中,都会使用
获得一个文件名d_entry = strdup(d->d_name);
并将指向 this 的指针添加到数组中:
srcList[aSz] = d_entry;
由于指针数组需要有有效的内存来指向我不能这样做:
d_entry = strdup(d->d_name);
srcList[aSz] = d_entry;
free(d_entry);
在最后一次使用数组后使用 free(d_entry) 只会释放 strdup/malloc 为最后一个 d_entry 实例分配的内存。
Valgrind 确认内存泄漏。
有没有办法解决这个问题,或者我应该考虑在数组中创建指针之前使用 memcpy 将文件名移动到单独的缓冲区。
核心循环:
for (bpos = 0; bpos < nread;) {
d = (struct linux_dirent *) (buf + bpos);
d_type = *(buf + bpos + d->d_reclen - 1);
if( d->d_ino != 0 && d_type == DT_REG || d_type == DT_UNKNOWN ) {
/* get directory entry */
d_entry = strdup(d->d_name); // << repeat allocations here
/* save pointer to filename in array 'srcList' */
srcList[aSz] = d_entry;
aSz++;
}
if ( aSz == DAY_COUNT +1 ) break;
bpos += d->d_reclen;
}
【问题讨论】:
-
当您不再需要
free()srcList[]中的条目时,请确保它们? -
你为什么不稍后迭代你的数组并释放所有东西?
-
每次拨打
strdup,您都需要拨打free一次,迟早 -
@anita2R 指针在你的
srcList.... -
所以? NULL 小b...blighters。
标签: c memory-leaks strdup