new分配了多少字节? [英] How many bytes were allocated by new?

查看:219
本文介绍了new分配了多少字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何在malloc之后获取内存块长度?

Possible Duplicate:
How to get memory block length after malloc?

如果我有一个指针,是否可以了解new分配了多少字节? 当我用Google搜索时,找到了针对Windows:_msize()和针对Mac:malloc_size()的解决方案.但是对于Linux没有任何帮助.

If I have a pointer, is it possible to learn how many bytes were allocated by new? When I googled I found a solution for Windows: _msize() and for Mac: malloc_size(). But nothing for Linux.

如果没有,有人知道为什么对程序员隐藏它吗? delete当然应该知道这样的信息.

And if not, does anybody know why is it hidden from a programmer? delete should definitely know such info.

更新:

据我所知,如果我有此代码:

As far as I know, if I have this code:

 class A {   
   ~A() {}
   int m_a; 
 }; 
 class B : public A {
   ~B() {}
   int m_b; 
 };

 int main() {   A * b = new B();   delete b;   return 0; }

将调用A的析构函数,但仍将释放new分配的所有内存. 这意味着仅知道指针就可以以某种方式进行计算.那么对程序员隐藏它的原因是什么呢?

Destructor of A will be called, but still all the memory allocated by new will be freed. This means that it can be somehow computed knowing only the pointer. So what is the reason for hiding it from a programmer?

推荐答案

不幸的是,没有 portable 方式来获取newmalloc分配的字节数.造成这种情况的原因有很多:

Unfortunately, there is no portable way of obtaining the number of bytes allocated by new and malloc. There are a number of reason why this is the case:

  • 在某些平台上,deletefree根本不执行 .因此,它们不需要存储大小信息.令人惊讶的是,这在嵌入式平台中很常见.只要您不进行过多分配,它就可以使您使用为其他平台编写的C或C ++代码,而无需进行过多分配.
  • 即使在更常见的平台上,系统分配的字节数也可能与您要求的不同.通常,您的分配将与更大的尺寸对齐-可能比原始请求大 .存储元数据也可能存储在非常慢的数据结构中-您不想使用时间紧迫的代码进行锁定并访问哈希表.
  • On some platforms, delete and free do nothing at all. As such, they don't need to store size information. This is surprisingly common in embedded platforms; it lets you use C or C++ code written for other platforms unchanged, as long as you don't do too much allocation.
  • Even on more common platforms, the system may allocate a different number of bytes than you ask for. Typically your allocation will be aligned to some larger size - possibly much larger than your original request. The storage metadata might also be stored in a very slow data structure - you wouldn't want to be taking locks and accessing a hash table in time-critical code.

作为可移植语言,C和C ++无法提供在每个平台上都不可用(或定义明确或相当快)的功能.这就是为什么在C ++上不可用.就是说,您不需要这个-C ++提供了std::vector(可以 跟踪您的分配大小),或者是std::string可以为您处理所有这些细节.

As portable languages, C and C++ can't offer a feature that won't be available (or well-defined, or reasonably fast) on every platform. That's why this is not available on C++. That said, you don't need this - C++ offers std::vector, which does track the size of your allocation, or std::string which takes care of all of those details for you.

这篇关于new分配了多少字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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