So, first off, this is an assignment for a friend that I’m helping with, and while it’s been a while since I’ve done C, that’s not the problem (Or at least I don’t think it is), the problem is the assembly code. The assignment must use a function written in inline assembly to sum two numbers that have been passed to the function after having been input by the user, and return the value, which is then output. On running my code, I get errors either reading or writing to memory locations found in the asm function, specifically the second mov command, and the program will hang while attempting to execute that line of code. Tracing the program, one of the values will be stored correctly (Whatever the second value the user enters, which I believe is normal, because values are read in reverse in assembly?) and the other isn’t read at all, and the program crashes. I’ve spent about four hours trying to figure this out, and am now resorting to outside help. Anyways, enough background, trying to be thorough, here’s the code. I’m sure what I’m doing is probably something basic and is staring me in the face, but any help is appreciated. Oh, and yes, I made sure masm was enabled in visual studio.
#include "stdafx.h"
#include "stdio.h"
#include <conio.h>
int sum( int val1, int val2 );
int main (void)
{
int val1=0, val2=0, val3=0;
printf("Hello, this program will add two whole numbers. Please enter the first number.\n");
scanf("%d",&val1);
printf("Please enter the second number.\n");
scanf("%d",&val2);
val3 = sum(val1, val2);
printf("The sum of %d and %d is %d", val1, val2, val3);
_getch();
return 0;
}
int sum ( int val1, int val2 ){
int val3;
__asm{ mov eax, val2 ;
push eax ;
mov ebx, val1 ;
push ebx ;
add eax, ebx ;
mov ecx, val3 ;
pop val3 ;
pop ebx ;
pop eax ;
pop ecx ;
ret ;
}
return val3;
}
I’m not sure what all the push and pops are for, but this works: