C++ overloaded new[] query : What size does it take as parameter?

匆匆过客 提交于 2019-12-23 08:54:22

问题


I have overloadded operator new[] like this

void * human::operator new[] (unsigned long int count){
      cout << " calling new for array with size  = " << count <<  endl  ;
      void * temp = malloc(count) ;  
      return temp ; 
}

and now calling

human * h = new human[14] ;

say sizeof(human) = 16 , but count it prints is 232 which is 14*16 + sizeof( int * ) = 224+8 .

Why is this extra space being allocated ? And where does it fall in memory ? Because when I print *h OR h[0] I get same results , so its not in beginning of memory chunk. Is it correct at all OR I am missing some thing here ?


回答1:


The extra space allocated is used to store the size of the array for internal usage (in practice so that delete[] knows how much to delete).

It is stored at the beginning of the memory range, immediately before &h. To see this, just look at the value of temp inside your operator new[]. The value will differ from that in &h.




回答2:


It is to store the number of objects allocated so that when you invoke delete[] proper number of objects are deleted. See this FAQ for more details.



来源:https://stackoverflow.com/questions/4012524/c-overloaded-new-query-what-size-does-it-take-as-parameter

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