【发布时间】:2018-07-13 02:12:03
【问题描述】:
我真的很难尝试使用 malloc 和 realloc 创建一个结构数组。我主要发布了整个代码库,或者至少发布了与以下问题相关的信息。
struct _section {
char *sectName;
int start_addr;
int end_addr;
char *bytes;
};
struct _section *get_exe_sections(struct _section *exe_sect, Elf *elf, GElf_Ehdr *ehdr, GElf_Shdr *shdr, Elf_Data *data) {
exe_sect->sectName = elf_strptr(elf, ehdr->e_shstrndx, shdr->sh_name);
exe_sect->start_addr = shdr->sh_addr;
exe_sect->end_addr = shdr->sh_addr + shdr->sh_size;
exe_sect->bytes = (unsigned char *)data->d_buf;
return exe_sect;
}
int main(int argc, char *argv[]) {
Elf *elf;
int fd;
//process input file
int sections_count = count_sections(elf);
GElf_Ehdr ehdr_mem;
GElf_Ehdr *ehdr = gelf_getehdr(elf, &ehdr_mem);
struct _section *exe_sect = (struct _section *)malloc(sizeof(struct _section));
for(int cnt = 0; cnt < sections_count; cnt++) {
Elf_Scn *scn = elf_getscn(elf, (size_t)cnt);
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
Elf_Data *data = elf_getdata(scn, NULL);
if(ehdr == NULL || shdr == NULL)
exit(1);
if(strcmp(header_name(SECT_TYPE, GELF_ST_TYPE(shdr->sh_type)), "PROGBITS") == 0) {
if(strcmp(flag_name(SECT_FLAGS, shdr->sh_flags), "ALLOC & EXECUTE") == 0 || \
strcmp(flag_name(SECT_FLAGS, shdr->sh_flags), "EXECUTE") == 0) {
exe_sect = get_exe_sections(exe_sect, elf, ehdr, shdr, data);
struct _section *nxt_sect = (struct _section *)realloc(exe_sect, 2*sizeof(*exe_sect));
if(nxt_sect != NULL)
exe_sect = nxt_sect;
}
}
}
return 0;
}
我遇到的问题是动态创建结构数组并使用malloc 和realloc 调整结构大小以适应更多数据。如果我要在main 的底部放置一些打印语句,则输出将为我提供最后输入到结构中的数据。我将如何访问在每次调用 get_exe_section 期间创建的各个条目?从之前的帖子和其他资源中,我认为这会起作用,但我无法以这种方式创建数组。任何形式的帮助都会很棒。谢谢。
【问题讨论】:
-
2*sizeof(*exe_sect)等价于2*sizeof(struct _section)。所以,你的realloc总是分配2*sizeof(struct _section)内存大小。 -
因此,您可能需要
2 * how_many_sections_I_already_have * sizeof(*exe_sect),而不是2*sizeof(*exe_sect)。您需要自己跟踪how_many_sections_I_already_have;没有明确的方法可以通过检查对象本身来确定分配对象的大小。 -
不能通过每次
get_exe_sections返回时增加一个值并用它来计算我有多少个部分来完成吗?
标签: c arrays malloc structure realloc