动态分配的数组的大小是否存储在某处? [英] Is the size of a dynamically-allocated array stored somewhere?

查看:134
本文介绍了动态分配的数组的大小是否存储在某处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来, delete [] 知道动态分配的数组的大小。我的问题是:有什么办法得到它,使我们不需要在编码时显式地提供大小。

It seems to me that delete[] knows the size of a dynamic allocated array. My question is: Is there any way to get it out so that we don't need to provide the size explicitly when coding.

推荐答案

已编辑:

由于delete []需要调用析构函数对于数组的所有元素,长度必须绝对存储在某处。至于为什么这个内存是不可访问的,以防止错误,如走阵列,由于其未知的大小 - 我不是很确定。严格地说,静态分配数组的长度必须在编译期间是已知的,并且动态分配的数组的长度必须由运行时存储,因此在这两种情况下,缓冲区溢出错误在理论上可100%防止,而静态和动态数组不安全。我的猜测是这是为了性能目的,边界检查将使它更慢,原始(C风格)数组在零安全性提供最佳性能。

Since delete [] needs to call destructors for all elements of the array, the length must definitely be stored somewhere. As of why this memory is not accessible to prevent errors such as walking outside of the array due to its unknown size - I am not really sure. Strictly speaking, the length of statically allocated arrays must be known during compile time and the length of dynamically allocated arrays must be stored by the runtime, so in both cases buffer overflow errors are theoretically 100% preventable, and yet both static and dynamic arrays are unsafe. My guess is this is for performance purposes, bounds checking will make it slower and raw (C style) arrays offer best performance at zero safety.

编译器和运行时供应商,可能有一些实现它可以被访问和使用,但它不会被认为是标准和推荐的做法。要存储长度的逻辑位置是在分配的内存片段的头部中的某个位置,即您将获得该数组的第一个元素的实际地址。

The implementation of this varies with compiler and runtime vendors, there might be some implementations it may be accessible and usable, but it wouldn't be considered standard and recommended practice. The logical place for the length to be stored is somewhere in the header of the allocated memory fragment before the actual address you will get for the first element of the array.

这篇关于动态分配的数组的大小是否存储在某处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆