1

I'm having an issue with a program I'm writing in NASM using SASM, I'm using a variable as a counter and once I modified it and try to to save the new value at the used address in memory I get a segmentation fault. Here are the bits of code concerning the variable:

section.data
p_count DW 0

section.text
global CMAIN
CMAIN:
    mov ebp, esp; for correct debugging
    mov bx, [p_count]
    inc bx
    mov [p_count], bx

    ret

The program stops running when it arrives at the last line here. Anyone has an idea what the problem could be?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
corlo407
  • 11
  • 5

1 Answers1

3

You forgot the space in section.data (and .text), so everything went into the read-only .text section by default.

section.data is parsed as a label, like foo.bar: would be, not a section directive. The colon at the end of a label is optional when the label name isn't also a valid instruction mnemonic like loop:

The opposite error (valid section .data but buggy section.text) leads to putting your code into the .data, which gets linked into non-executable memory pages. In that case you'd segfault on code-fetch from the first instruction!


You should have gotten a warning from NASM like this:

warning: label alone on a line without a colon might be in error [-w+orphan-labels]

If your NASM didn't warn, use a newer version where it's on by default,
or run NASM with -Worphan-labels to enable that useful warning.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • Related: [Code works when run from section .data, but segmentation faults in section .text](https://stackoverflow.com/q/38152352) is that opposite error, with code in .data (which happens to work if built in a way that makes .data executable). Also [x86\_64 Assembly - Segfault when trying to edit a byte within an array in x64 assembly](https://stackoverflow.com/q/45005078) is a good canonical duplicate for questions without a section directive at all, rather than a failed attempt to use the .data section. – Peter Cordes Jul 30 '22 at 00:06