Should I always use size_t when indexing arrays?

安稳与你 提交于 2021-02-07 11:24:35

问题


Do I need to use size_t always when indexing an array even if the array is not big enough to exceed the size of an int?

It's not a question about when I should use size_t. I just want to know if, for example, a program having 2GB of available memory (all of these fields can be indexed by an int32) but with this memory being (virtual memory) assigned to the "fields" 14GB - 16GB of the computer's RAM.

Would it always fail when indexing the memory if I used an int32 instead of a size_t (or an unsigned long int) in this case?

Maybe the question is more about virtual memory than about pointers.


回答1:


size_t is an unsigned integer that is capable of holding the size of the largest object you can allocate. It is useful for indexing because this means it can index into the largest array you can allocate.

This does not mean it is required or even necessarily recommended for indexing. You can use any integer type that is large enough to index the array. int_fast32_t might be faster, uint_least16_t might be smaller in a structure, and so on. Know your data, and you can make a good choice.

Virtual memory is outside the scope of C or C++. From their point of view, you simply index into memory and it's up to your platform to make it work. In practice your app only uses virtual addresses; your CPU/OS is translating the virtual address to a physical address behind the scenes. It is not something you need to worry about.




回答2:


In order to avoid program failures the programmer should always use an index type that is at least as large as the type returned by the size() method. This ensures that the index never overflows any possible size of the array. The implementation of an array is usually making sure that its runtime size never overflows the type returned by the size() method. This means the index type should be:

  • size_t in case of char[N], uint8_t[N], int[N], etc
  • size_t in case of std::vector and std::list
  • int in case of QList and QVector
  • an arbitrary precision integer (aint) in case of bitarrays (if the bitarray's size() method returns an aint)
  • aint in case of arrays compressed in memory (if the array's size() method returns an aint)
  • aint in case of arrays spanning multiple machines (if the array's size() method returns an aint)
  • Other languages than C++:
    • int in case of java.util.Collection and its subclasses

In summary: A safe index type is the type returned by the size() method.

Note: If the size() method returns the unsigned size_t, then the signed int and ssize_t aren't safe index types. In case of gcc and clang, the compiler flags -Wsign-compare (enabled by -Wall) and -Wconversion can be used to prevent most of these cases.



来源:https://stackoverflow.com/questions/55604029/should-i-always-use-size-t-when-indexing-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!