-3

我在许多书中看到这句话,C/C++ 中数组的主要问题之一是:

数组需要一个连续的内存块

我真的不明白为什么 Arrays 的这个功能会考虑问题?我认为编译器可以管理并为数组分配正确的大小,那么问​​题是什么?

4

4 回答 4

0

The reason why a contigious block is an important feature is, when you call functions in the operating system, they usually expect the whole buffer being one byte after the other. For your own code it may not be a problem, because the array implementation can encapsulate the access to it, so that multiple smaller chunks could be presented to the outside as if it were ocntigious. Passing that memory to other functions, which don't know about your particular implementation, this no longer holds true.

Another, smaller issue, may be performance when accessing the array.

于 2013-08-02T20:23:39.347 回答
0

说起来这不是问题,但这意味着必须在内存中找到一个连续的块才能为数组获取空间。如果您的记忆非常碎片化,这可能会很棘手。话虽这么说,数组必须是连续的通常非常好,因为这意味着您可以定期访问内存并减少缓存未命中,从而创建缓存友好的代码

另一方面,现在有像链表这样的结构,其中包含指向其他元素的指针,这意味着它们可以位于内存的不同部分并且不必是连续的,但这也意味着当您尝试访问指针时可能没有被缓存,因此您有一个缓存未命中延迟程序。

于 2013-08-02T20:17:54.387 回答
0

当您考虑内存碎片的情况时,您可能无法找到满足整个数组大小要求的空闲内存块。

这在某些分配/释放方案中尤其容易看到,其中数千个可变大小的对象被快速分配和释放,这可能会在空闲内存中留下多个漏洞(取决于使用的策略)。此时,大对象的不合时宜分配可能无法找到任何可用空间。

于 2013-08-02T20:18:15.437 回答
0

碎片整理发生在内存中,然后在尝试分配内存时,您可能没有所需的正确大小。

于 2013-08-02T20:19:16.483 回答