【发布时间】:2025-12-15 01:55:01
【问题描述】:
查看e2fsprogs 的源代码,想了解内部存储器例程的使用。分配和释放。
更重要的是为什么使用memcpy而不是直接处理?
分配
例如ext2fs_get_mem 是:
/*
* Allocate memory. The 'ptr' arg must point to a pointer.
*/
_INLINE_ errcode_t ext2fs_get_mem(unsigned long size, void *ptr)
{
void *pp;
pp = malloc(size);
if (!pp)
return EXT2_ET_NO_MEMORY;
memcpy(ptr, &pp, sizeof (pp));
return 0;
}
我猜使用局部变量是为了不使传递的ptr 失效,以防出现malloc 错误。
- 为什么
memcpy而不是设置ptr为pp成功?
免费
内存被复制到一个局部变量,然后被释放,然后memcpy 在传递的指针上。由于分配使用memcpy,我猜它还必须在 free 上做一些杂耍。
- 不能直接释放吗?
- 最后一个
memcpy是做什么的?sizeof(p)这里不是int的大小吗?
/*
* Free memory. The 'ptr' arg must point to a pointer.
*/
_INLINE_ errcode_t ext2fs_free_mem(void *ptr)
{
void *p;
memcpy(&p, ptr, sizeof(p));
free(p);
p = 0;
memcpy(ptr, &p, sizeof(p));
return 0;
}
使用示例:
ext2_file_t 定义为:
typedef struct ext2_file *ext2_file_t;
ext2_file has,以及其他成员,char *buf。
我们有:
ext2_file_t e2_file;
retval = ext2fs_file_open(current_fs, ino, 0, &e2_file);
它调用ext2fs_file_open() 来做:
ext2_file_t file;
retval = ext2fs_get_mem(sizeof(struct ext2_file), &file);
retval = ext2fs_get_array(3, fs->blocksize, &file->buf);
而免费例程例如:
if (file->buf)
ext2fs_free_mem(&file->buf);
ext2fs_free_mem(&file);
【问题讨论】:
标签: c memory memory-management malloc free