ARM汇编str指令触发段错误求助:新手代码排查
str Instruction Hey there! Let's break down why that str instruction is throwing a segmentation fault for you.
The Root Cause
Looking at your code, all your variables (var1, var2, var3) are placed directly in the .text segment. Here's the key problem: the .text segment is marked as read-only by default in ELF executable files. When you try to write to var3 using str r1,[r11],#4, you're attempting to modify a read-only memory region—this triggers the segmentation fault you're seeing.
Your adr r11,var3 is correctly loading the address of var3, but that address lives in a part of memory you don't have permission to write to.
The Fix: Move Variables to a Writable Segment
To fix this, you need to move your variables into the .data segment (for initialized, writable data) or .bss segment (for uninitialized data that gets zero-initialized automatically). Here's the adjusted code:
exam.s .text .global main main: adr r3, var1 ldr r0, [r3] mov r0,r0, LSL #2 adr r3, var2 ldr r1, [r3] and r1,r1,#15 orr r1,r0,r1 adr r11,var3 str r1,[r11],#4 mov r0,#0 mov r7,#1 swi 0 .data @ Switch to the writable data segment var1: .word 10 var2: .word 20 var3: .word 0
Quick Additional Notes
.datais ideal for pre-initialized variables that need read/write access—perfect for yourvar1,var2, andvar3since they all have explicit initial values.- If you had a variable that didn't need an initial value (like an empty buffer), you could use
.bssinstead—it doesn't take up space in your executable file and gets set to zero automatically by the OS. - When compiling, use your ARM cross-compiler (e.g.,
arm-linux-gnueabi-gcc exam.s -o exam) to ensure the linker correctly handles the segment permissions.
内容的提问来源于stack exchange,提问作者최재혁

