开发者

determine length of calloc array of TCHARs (not string length) [duplicate]

This question already has answers here: Determine size of dynamically allocated memory in C (15 answers) Close开发者_StackOverflow社区d 9 years ago.

I have this code:

TCHAR *sRes;
sRes = (TCHAR *) calloc(16384, sizeof(TCHAR));
DWORD dwRes = sizeof(sRes);

dwRes is always 8, and of course _tcslen(sRes) is always 0.

I am looking for 16384.


In C there is no way to get the size of a memory block with only the base address of the block.

But when you created the block, you knew the size: just save it and use it afterwards when you need:

TCHAR *sRes;
DWORD dwRes = 16384 * sizeof (TCHAR);
sRes = calloc(16384, sizeof (TCHAR)); /* I prefer `sizeof *sRes` */

/* use `sRes` and `dwRes` as needed ... */

Also, notice I removed the cast from the return value of calloc. Casting here serves no useful purpose and may hide an error.


There is no supported mechanism for obtaining size of a block allocated with malloc or calloc. If you call HeapAlloc instead you may call HeapSize thereafter.


The operating system and the underlying memory allocator implementation keep track of that number, but there is no standard facility to obtain this value in application code.

sizeof is a static operator and hence cannot be used to return the size of anything that's determined at runtime.

Your only option is to create a custom struct where you manually keep both the returned pointer and the size which was allocated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜