C语言 向结构数组添加值会导致 Seg 错误



所以我有一个程序,我在其中制作一个结构数组,然后我遍历每个结构并将值插入到每个结构中。唯一的问题是,当我尝试插入这些值时,我遇到了分段错误。原谅我,我是一个新手C程序员,但我环顾四周,找不到问题的答案。

以下是代码(为简单起见进行了重构(:

#include "readelf.h"

int main(int ac, char **av)
{
int elf_shnum, sh_name_index, i;
Section_t *sections;
i = 0;
elf_shnum = 12;
sh_name_index = 24;
sections = malloc(elf_shnum * sizeof(Section_t));
sections[i].header->sh_name = sh_name_index;
return (0);
}

包含文件:

#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdint.h>
#include <elf.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
typedef struct
{
uint64_t  sh_name;                /* Section name (string tbl index) */
uint64_t  sh_type;                /* Section type */
uint64_t  sh_flags;               /* Section flags */
uint64_t  sh_addr;                /* Section virtual addr at execution */
uint64_t  sh_offset;              /* Section file offset */
uint64_t  sh_size;                /* Section size in bytes */
uint64_t  sh_link;                /* Link to another section */
uint64_t  sh_info;                /* Additional section information */
uint64_t  sh_addralign;           /* Section alignment */
uint64_t  sh_entsize;             /* Entry size if section holds table */
} Elf_Big_Shdr_t;
typedef union
{
Elf32_Shdr Elf32;
Elf64_Shdr Elf64;
} Elf_Shdr_t;
typedef struct
{
Elf_Big_Shdr_t *header;
unsigned char *data;
} Section_t;

你Section_t表,没关系,

sections = malloc(elf_shnum * sizeof(Section_t));

但是这个结构包含下一个指针Header

typedef struct
{
Elf_Big_Shdr_t *header;
unsigned char *data;
} Section_t;

在使用它之前,您应该为其分配内存。

例如:

sections[i].header = malloc(sizeof(Elf_Big_Shdr_t));
sections[i].header->sh_name = sh_name_index;

或者,您可以将结构定义更改为

typedef struct
{
Elf_Big_Shdr_t header;
unsigned char *data;
} Section_t;

sections = malloc(elf_shnum * sizeof(Section_t));

分配一堆数据,并将其存储到sections。分配的内存中的实际数据是不确定的。然后,在您的下一行

sections[i].header->sh_name = sh_name_index;

你尝试将一些内存(sections[0].header(视为指针并取消引用它。但是,由于该值是不确定的,因此这是未定义的行为。最可能且问题最少的结果是段错误。

相反,您需要在使用之前为每个Section_t分配有用的值。您可以通过为 Elf 标头malloc足够的空间并将结果分配给sections[i].header来做到这一点,但除非 Elf 部分可以有多个标头或零标头,否则最好让header成员具有类型Elf_Big_Shdr_t而不是Elf_Big_Shdr_t *

最新更新