やりたいこと
C言語で
int*型を用いてintの配列をつくり、
その配列の長さを取得したいです。
mallocで確保した領域の長さが分かれば良いのですが、
malloc_usable_sizeという関数が動きません。
malloc_usable_sizeの動かし方、
もしくは同等の結果を得る別の方法があれば教えていただきたいです。
試したこと
ソースコード(下に添付)8行目のように、sizeofで計算しようとすると、
sizeof(p)がint*のサイズを返してしまうため、lenにかかわらず8を返してしまいます。
また、mallocで確保した領域のサイズを返す、malloc_usable_sizeという関数があるようですが、malloc.hのincludeでエラーが出ます。
発生している問題・エラーメッセージ
以下エラーメッセージです。
pointer.c:3:10: fatal error: 'malloc.h' file not found #include <malloc.h> ^~~~~~~~~~ 1 error generated.
該当のソースコード
C
1#include <stdio.h> 2#include <stdlib.h> 3#include <malloc.h> 4 5int main(int argc, char const *argv[]) { 6 int len = 12; 7 int *p = malloc(sizeof(int) * len); 8 int p_size = sizeof(p)/sizeof(int); 9 printf("%d\n",p_size); 10 printf("%d\n",malloc_usable_size(p)); 11 free(p); 12 return 0; 13}
環境
OS X 10.13.2

回答4件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/03/27 00:07
2018/03/27 00:10
2018/03/27 00:12