# Wrong result of 'ddot' from BLAS

I am having trouble with a C/C++ program that uses the BLAS routine ddot. I am running Linux and so far LAPACK routines worked without any problems.

I get a wrong result, no matter if I choose the type int for integer arguments of ddot or if I choose ptrdiff_t.

The Code is:

#include <iostream>
#include <stdlib.h>
using namespace std;

extern "C" {
extern int ddot_( int*, double* , int* , double* ,int*);
// OR extern int ddot_( ptrdiff_t*, double* , ptrdiff_t* , double* ,ptrdiff_t*);
}

int main() {
int n=3; // OR ptrdiff_t  n=3;
int inc=1; // OR ptrdiff_t inc=1;
double result=0;

double *x = (double*) calloc (n, sizeof (double));
double *y = (double*) calloc (n, sizeof (double));

result = ddot_(&n, x, &inc, y, &inc);
cout<<result<<endl;
return 0;
}


If I choose n and inc to be of type int everything compiles but I get the output that result is equal to 4. Same effect with different number for x and y.

I tried to google my question and found out that the type of n and inc might cause wrong results and I should try ptrdiff_t or mwSignedIndex. I didn't manage to include mwSignedIndex in my program so far but if I choose n and inc to be of type ptrdiff_t and change the "extern C" part in the beginning I get 4as a result aswell.

Am I missing something? Is my math wrong? I appreciate any help or suggestions!

EDIT: in a former version of the question I didn't manage to properly use the ptrdiff_t. Nevertheless the wrong result is still there.

• Why not #include <cblas.h>? – Kirill Nov 7 '18 at 23:23

The strange thing in your code is ddot_ being declared as extern C int, while it is actually a double-valued function. And its value is assigned to a double variable result. Those conversions are probably what is causing your issues (I am not entirely sure how did it compile and passed the -Wall compiler flag – I hope you are using one).
n and inc being ints should be fine, unless you are not doing something very specific with a specifically configured version of BLAS on a particular architecture.
• Arrrg... now I feel a little embarrassed for such a stupid mistake. I copy&pasted that part and forgot to adjust it accordingly. And yes, I used -Wall and some other flags but there we no warnings and everything compiled smoothly. Thank you very very much for helping me again! – Blablablu Nov 7 '18 at 22:20
• @Blablablu It's not the compiler's business: when you link to a library that exports ddot_ with a different type (and it's a C function, so no name mangling like with C++), the compiler cannot do anything because it doesn't see what's inside the library, and the linker can't do anything because it doesn't know about types. So no warning. Explaining the value it "returns" is complicated: it assumes the int is returned in the eax register, but ddot returns a double in an xmm register, so it just reads whatever was in the eax register after ddot. (I think.) – Kirill Nov 7 '18 at 23:06