# Examples of MKL_malloc(), MKL_free(), MKL_MemStat() Usage

## Usage Example in Fortran

PROGRAM FOO

REAL*8 A,B,C

POINTER (A_PTR,A(1)), (B_PTR,B(1)), (C_PTR,C(1)

INTEGER N, I

REAL*8 ALPHA, BETA

INTEGER ALLOCATED_BYTES

INTEGER ALLOCATED_BUFFERS

INTEGER MKL_MEMSTAT, MKL_MALLOC

EXTERNAL MKL_MALLOC, MKL_FREE, MKL_MEMSTAT

ALPHA = 1.1; BETA = -1.2

N = 1000

A_PTR = MKL_MALLOC(8*N*N,128)

B_PTR = MKL_MALLOC(8*N*N,128)

C_PTR = MKL_MALLOC(8*N*N,128)

DO I=1,N*N

A(1) = I

B(1) = -I

C(1) = 0.0

END DO

CALL DGEMM('N','N',N,N,N,ALPHA,A,N,B,N,BETA,C,N);

ALLOCATED_BYTES = MKL_MEMSTAT(ALLOCATED_BUFFERS)

PRINT *,'DGEMM uses ',ALLOCATED_BYTES,' bytes in ',

$ ALLOCATED_BUFFERS,' buffers '

CALL MKL_FREEBUFFERS

ALLOCATED_BYTES = MKL_MEMSTAT(ALLOCATED_BUFFERS)

IF (ALLOCATED_BYTES > 0) THEN

PRINT *,'MKL MEMORY LEAK!'

PRINT *,'AFTER MKL_FREEBUFFERS there are ',

$ ALLOCATED_BYTES,' bytes in ',

$ ALLOCATED_BUFFERS,' buffers'

END IF

CALL MKL_FREE(A_PTR)

CALL MKL_FREE(B_PTR)

CALL MKL_FREE(C_PTR)

STOP

END

## Usage Example in C

#include <stdio.h>

#include <mkl.h>

int main(void) {

double *a, *b, *c;

int n, i;

double alpha, beta;

MKL_INT64 AllocatedBytes;

int N_AllocatedBuffers;

alpha = 1.1; beta = -1.2;

n = 1000;

a = (double*)MKL_malloc(n*n*sizeof(double),128);

b = (double*)MKL_malloc(n*n*sizeof(double),128);

c = (double*)MKL_malloc(n*n*sizeof(double),128);

for (i=0;i<(NN*NN);i++) {

a[i] = (double)(i+1);

b[i] = (double)(-i-1);

c[i] = 0.0;

}

dgemm('N','N',&n,&n,&n,&alpha,a,&n,b,&n,&beta,c,&n);

AllocatedBytes = MKL_MemStat(&N_AllocatedBuffers);

printf('\nDGEMM uses %ld bytes in %d buffers',(long)AllocatedBytes,N_AllocatedBuffers);

MKL_FreeBuffers();

AllocatedBytes = MKL_MemStat(&N_AllocatedBuffers);

if (AllocatedBytes > 0) {

printf("\nMKL memory leak!");

printf("\nAfter MKL_FreeBuffers there are %ld bytes in %d buffers",

(long)AllocatedBytes,N_AllocatedBuffers);

}

MKL_free(a);

MKL_free(b);

MKL_free(c);

return 0;

}

Parent topic: Memory Functions