使用 malloc 创建的数组如何与缓存交互?

How do arrays created with malloc interact with cache?

假设我现在已经使用代码创建了一个矢量

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

//Initialize a

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

我猜想在计算 b 时,a[i] 将在每个 i 的缓存中单独传输,对吗?

使用 double a[64] 而不是 malloc 创建 a 怎么样?整个数组会同时放入缓存吗?

提前致谢。

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

如果使用double a[64]声明,则需要同时放入Stack

如果使用malloc分配内存,则应同时放入Heap

只是内存位置不同。

Demo

根据Demo,整个数组要同时放入HeapStack

另一方面,在malloc之后Size a输出65,原因是malloc_usable_size(void* ptr)问题。

(使用此功能只是想确定内存是否已经分配。)

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?

我不确定你的 cache 是什么意思,但是 a[i] 应该取自 HeapStack.