Home > Mobile >  How do arrays created with malloc interact with cache?
How do arrays created with malloc interact with cache?

Time:10-19

Let’s say I have now created a vector using code

double *a;
double b;
a = (double *)malloc(64*sizeof(double));

//Initialize a

for(int i = 0; i < 64; i  )
{
    b  = a[i];
}

I guess when computing b, a[i] will be transported in cache separately for each i, am i right?

And what about creating a using double a[64] instead of malloc? Will the whole array be put into cache at the same time?

Thanks in advance.

CodePudding user response:

And what about creating a using double a[64] instead of malloc? Will the whole array be put into cache at the same time?

If you use the double a[64] to declare, that should be put into the Stack at the same time.

If you use the malloc to assign memory, that should be put into the Heap at the same time.

Just the memory location is different.

Demo

According to Demo, the whole array shall be put into the Heap or Stack at the same time.

On the other hand, after malloc the Size a output 65 that reason is malloc_usable_size(void* ptr) problem.

(Using this function just want to make sure the memory whether already assigned.)

malloc_usable_size() description

The value returned by malloc_usable_size() may be greater than the requested size of the allocation because of alignment and minimum size constraints. Although the excess bytes can be overwritten by the application without ill effects, this is not good programming practice: the number of excess bytes in an allocation depends on the underlying implementation.

I guess when computing b, a[i] will be transported in cache separately for each i, am i right?

I not sure what your cache means, but a[i] should be taken from Heap or Stack.

  • Related