0

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
JeffR
  • 765
  • 2
  • 8
  • 23

3 Answers3

3

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.

pmg
  • 106,608
  • 13
  • 126
  • 198
  • But I get a compiler error if I don't cast it. – JeffR Apr 18 '11 at 20:41
  • 2
    Then you're probably compiling with a C++ compiler. I prefer to use C compilers for C code, but I understand some people like to compile C code with C++ compilers for extra (*redundant and possibly erroneous*) diagnostics. – pmg Apr 18 '11 at 20:44
  • Yes, I am compiling with a C++ compiler. @Blagovest: I'm using Visual Studio 2008. I get a "void *" compiler error. – JeffR Apr 18 '11 at 20:47
  • 2
    Using a C++ compiler for C code is like [speaking British english in the USA or vice-versa](http://en.wikipedia.org/wiki/American_and_British_English_differences#Words_and_phrases_with_different_meanings). Do it at your own risk. I think it is possible to configure Visual Studio as a C (C89) compiler. – pmg Apr 18 '11 at 20:54
0

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.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
  • I read HeapAlooc will get the memory from the process default heap. calloc will get the memory from CRT heap. What's the implications of usage of either one? – JeffR Apr 18 '11 at 20:16
  • You to free HeapAlloc memory with HeapFree. I also suspect that it's slower, but it's been a long time. – bmargulies Apr 18 '11 at 20:18
0

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.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130