Author Topic: Sum array with numeric coprocessor  (Read 18753 times)

Offline akus85

  • Jr. Member
  • *
  • Posts: 5
Sum array with numeric coprocessor
« on: May 17, 2010, 04:09:45 PM »
Hi,i try to sum the elements of array using numeric coprocessor it works,but don't print the correct value...  ::) (i obtain tot=858993459.0  instead of tot=11.1)

This is the code: driver.c
Code: [Select]
                                                                                     
#include <stdio.h>
#define N 3

double main(){
  double ret_status;
  double A[N]={2.2,3.3,5.6};
  int i;

  printf("Array:\n");
  for (i=0;i<N;i++) printf("%.1f ",A[i]);
  printf("\n");

  ret_status=_sum(A,N);

  printf("tot=%.1f\n",ret_status);
  return ret_status;
}

sum.asm
Code: [Select]
%include "asm_io.inc"

%define A [ebp+8]
%define N [ebp+12]

segment .bss
tot resq 1

segment .text
global _sum
_sum:
enter 0,0

mov ecx,N
mov esi,A
fldz ; Set 0 ST0
lp:
fadd qword [esi] ; ST0=ST0+[esi]
add esi,8 ; increase esi
loop lp

dump_math 1
fstp qword [tot]

mov eax,[tot]

leave
ret

Offline Frank Kotler

  • NASM Developer
  • Hero Member
  • *****
  • Posts: 2667
  • Country: us
Re: Sum array with numeric coprocessor
« Reply #1 on: May 17, 2010, 05:03:10 PM »
I think your problem is with return types. I'm not much good at C, but I believe "main" returns "int", period.

In your asm code, you end with "mov eax, [tot]".  Considering "tot" is a qword (a.k.a. "double"), what's that supposed to do? Furthermore, you "fstp" st0 into "[tot]". I believe you want to leave your return value on the FPU stack - change it to "fst"... if you think you need to do that at all (I think "tot" could vanish entirely).

But I think your "main problem" (pun!), is that C needs to be advised that "_sum" will be returning a "double", so C should look on the FPU stack, not eax, for its return value...

Code: [Select]
double _sum(double *, int);

(before "main")

The fact that "dump_math" shows the correct value in st0 indicates that you're doing it right, so far, and that the problem is with the C code, I think. One or another of the changes I made (note to self: ';' does not make a comment in C!) seems to be printing the correct answer, and I think the key is the "prototype" of the function, so C knows it's returning "double", not "int"...

Best,
Frank


Offline akus85

  • Jr. Member
  • *
  • Posts: 5
Re: Sum array with numeric coprocessor
« Reply #2 on: May 17, 2010, 05:13:30 PM »
Ok thanks for the advices.  ;)