The question consists of an assembly program that takes an input from a C program and divides it by a number, and returns the remainder to the C program to be printed as a string.
Here is my code for both:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
char *str;
str = malloc(1<<9);
printf("Enter a number: ");
scanf ("%d", &i);
printf("Number: %i\n", i);
str=int2string(i);
printf("Number as string is: %s\n", str);
return 0;
}
ASM =
%include "asm_io.inc"
segment .data
segment .bss
buffer resd 4
segment .text
global int2string
int2string:
enter 0,0 ; setup routine
pusha
mov edx, 0
mov eax, [ebp+8] ; eax contains input value of int2string
mov ebx, 10 ; sets ebx to value of 10
div ebx ; eax = eax / ebx
call print_int ; prints eax = quotient
call print_nl ; next line
mov eax, edx ; store edx (remainder) in eax
call print_int ; print remainder
call print_nl ; next line
add eax, 48 ; convert result into ASCII character
popa
mov dword[buffer], eax ; move ASCII character (if I replace eax with 48-57
; it prints 0-9 correctly)
mov eax, buffer ; move buffer value to eax
leave
ret
My understanding is that the ASCII codes for numbers 0-9 is from the range 48-57, but if I don’t put the number explicitly in the buffer move, then the output is either garbage or segmentation fault.
Am I missing something here (eax with a value of 2 + 48, should be ASCII (50) = ‘2’)?
It’s likely that either
print_intorprint_nlmay not preserve the value ofeax(especially since a common calling convention is to return the result of a function in that register). If your second call toprint_intprints the right value but the character is wrong, that’s a distinct possibility.An easy test/fix for that is to change:
into:
Other than that, it looks okay. All I can suggest is to single step through the code to see where it’s going wrong.