尝试将地址复制到结构时出现分段错误?

Segmentation fault when attempting to copy an address into a struct?

我有一个 NASM 程序因分段错误而崩溃。

在文件的开头,定义了以下结构:

struc mystruct
    .myhandler resq 1
endstruc

.bss 部分中创建了一个结构实例:

section .bss

    inst resb mystruct

程序做的第一件事是尝试将标签的地址存储在结构的唯一字段中:

section .text
global _start

_start:

    lea rax, [handler]
    mov [inst + mystruct.myhandler], rax

handler:

    ; ...

根据GDB,leamov指令如下:

(gdb) disassemble _start
Dump of assembler code for function _start:
=> 0x0000000000400080 <+0>: lea    rax,ds:0x400090
   0x0000000000400088 <+8>: mov    QWORD PTR ds:0x601000,rax
...

但是,运行 应用程序导致分段错误:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400088 in _start ()

这是为什么?


编辑: 附加信息:

$ nm -S app.o
0000000000000010 t handler
0000000000000000 b inst
0000000000000000 a mystruct
0000000000000000 a mystruct.myhandler
0000000000000008 a mystruct_size
0000000000000000 T _start

$ size -A app.o
app.o  :
section   size   addr
.text     16      0
.bss       0      0
Total     16

Peter Cordes 在评论中指出:

It looks like inst resb mystruct is reserving 0 bytes in the BSS, so your process doesn't have a BSS at all. But it still assembles and links somehow. I don't know what the right syntax is for sizeof() in NASM; I never use its struct syntax.

原来我需要做的是改变:

act resb mystruct

...到...

act resb mystruct_size

此符号由汇编程序自动定义,并设置为结构的大小(以字节为单位)。

程序不再在那段代码上崩溃。