LoginSignup
3
1

More than 5 years have passed since last update.

sizeof

Last updated at Posted at 2018-12-21

配列のサイズを調べるのに、sizeofを使う、と良くあるが、
動的に確保した内容については、ポインタのサイズを返す、という内容。
あと、動的に確保した領域のサイズを知るためには、malloc_usable_sizeで見れる。

追記。
一応確保したサイズは、malloc_usable_sizeで見れますが、デバッグや内部調査目的以外に、
特に使う理由はないはずです。(malloc_usable_sizeのマニュアルにもそう書いてあります)

一応mallocか、それと同様な処理で確保されたポインタであれば問題なさそうですけど、
newの処理が、具体的に何をしているかは、ちょっと調査不足です。はい。

 

a.cpp
#include <iostream>
#include <malloc.h>

int main(int argc, char **argv) {
        char text[] = {98, 0, 99, 0, 100, 0};
        char *text2 = new char[100];

        std::cout << "sizeof text: " << sizeof(text) / sizeof(char) << std::endl;
        std::cout << "sizeof text2: " << sizeof(text2) / sizeof(char) << std::endl;
        std::cout << "malloc_usable_size text2: " << ::malloc_usable_size(text2) << std::endl;

        delete [] text2;
}

[todanano@localhost ~]$ g++ a.cpp
[todanano@localhost ~]$ ./a.out
sizeof text: 6
sizeof text2: 8
malloc_usable_size text2: 104
[todanano@localhost ~]$
3
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1