gpt4 book ai didi

c - malloc() 成功但分配的内存少于预期

转载 作者:太空宇宙 更新时间:2023-11-04 00:15:14 24 4
gpt4 key购买 nike

我使用malloc分配了8192字节的内存; malloc 成功返回,但由于某种原因,我无法访问该内存块的 4205 字节以外的内存。

我也试过分配更大的内存块(即 8192 * 2),但仍然没有成功,只有前 4205 字节的内存是可访问的:(

部分代码如下:

int num_ino = 256;
struct inode * ino_table = malloc(8192);
assert(ino_table);
for(int i = 0; i < num_ino; i ++){
printf("pre core dump %d\n", i);
memcpy(ino_table + i * sizeof(struct inode), &inotable[i], sizeof(struct inode));
}

这是 gdb 中发生的事情:

Breakpoint 1, unixfilesystem_init (dfd=3) at unixfilesystem.c:54
54 assert(ino_table);

(gdb) p *(ino_table)
$1 = {i_mode = 0, i_nlink = 0 '\000', i_uid = 0 '\000', i_gid = 0 '\000', i_size0 = 0 '\000', i_size1 = 0, i_addr = {0, 0, 0, 0, 0, 0, 0, 0},
i_atime = {0, 0}, i_mtime = {0, 0}}

(gdb) p *(ino_table + 4205)
$2 = {i_mode = 0, i_nlink = 0 '\000', i_uid = 0 '\000', i_gid = 0 '\000', i_size0 = 0 '\000', i_size1 = 0, i_addr = {0, 0, 0, 0, 0, 0, 0, 0},
i_atime = {0, 0}, i_mtime = {0, 0}}

(gdb) p *(ino_table + 8000)
Cannot access memory at address 0x643a30

(gdb) p *(ino_table + 4206)
Cannot access memory at address 0x625ff0

最佳答案

ino_table进行指针运算时,单位是sizeof(struct inode),不是byte。

因此,

ino_table + i * sizeof(struct inode)

应该变成

ino_table + i

最后,我将像这样更改 malloc():

struct inode * ino_table = malloc(num_ino * sizeof(struct inode));

关于c - malloc() 成功但分配的内存少于预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19376981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com