确定 TCHAR 的 calloc 数组的长度(不是字符串长度)
我有这样的代码:
TCHAR *sRes;
sRes = (TCHAR *) calloc(16384, sizeof(TCHAR));
DWORD dwRes = sizeof(sRes);
dwRes 始终为 8,当然 _tcslen(sRes) 始终为 0。
我正在寻找 16384。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C 语言中,无法仅通过块的基地址来获取内存块的大小。
但是,当您创建块时,您就知道了大小:只需保存它并在需要时使用它即可:
另外,请注意,我从
calloc
的返回值中删除了强制转换。此处的强制转换没有任何用处,并且可能会隐藏错误。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:
Also, notice I removed the cast from the return value of
calloc
. Casting here serves no useful purpose and may hide an error.没有支持的机制来获取使用 malloc 或 calloc 分配的块的大小。如果您调用
HeapAlloc
,则可以随后调用HeapSize
。There is no supported mechanism for obtaining size of a block allocated with malloc or calloc. If you call
HeapAlloc
instead you may callHeapSize
thereafter.操作系统和底层内存分配器实现会跟踪该数字,但没有标准工具可以在应用程序代码中获取该值。
sizeof
是一个静态运算符,因此不能用于返回运行时确定的任何内容的大小。您唯一的选择是创建一个自定义结构,在其中手动保留返回的指针和分配的大小。
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.