Hunter McMillen
Hunter McMillen

Reputation: 61515

x86 assembly - printing a character given an ascii code

I am new to assembly programming and am having trouble printing a character to the screen. Every time I execute my program I get a segmentation fault and I am not sure why.

.section .data
  A:
    .long  65  # ascii code for 'A'

.section .text
.globl _start

_start:
 movl $1, %edx # length of character to print, 1
 movl  A, %ecx # what I want printed
 movl $1, %ebx # file descriptor for STDOUT
 movl $4, %eax # syscall number for sys_write

 int $0x80     # calls kernel

 movl $0, %ebx # return status
 movl $1, %eax # syscall number for sys_exit

 int $0x80     # calls kernel

These are the commands I use to build (my file is named write.s)

as write.s -o write.o
ld write.o -o write

Is this not the correct way to print a character? Any help would be appreciated.

Upvotes: 3

Views: 5364

Answers (1)

Niklas B.
Niklas B.

Reputation: 95278

movl A, %ecx

means: Copy the value at the address of the label A into %ecx. The correct instruction would be:

movl $A, %ecx

or

leal A, %ecx

You can use GDB for debugging in these cases (note that you have to assemble with the -g flag to get debug information):

$ as -g write.s -o write.o
$ ld write.o -o write
$ gdb write
GNU gdb (GDB) 7.5
   [.. snip ..]
(gdb) b test.s:13
Breakpoint 1 at 0x4000c6: file test.s, line 13.
(gdb) run
Starting program: /home/niklas/tmp/asm/write 

Breakpoint 1, _start () at test.s:13
13   int $0x80     # calls kernel
(gdb) info registers ecx
ecx            0x41 65

As you see, %ecx has the integer value 65, which is not what you want.


If you run strace ./write, it will decode the system call args and return value for you. You'll see that write() just returns -EFAULT without doing anything else when you pass it a bad pointer.

Upvotes: 2

Related Questions