Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Obtaining memory block size

Status
Not open for further replies.

DustyMx

Programmer
Jan 10, 2005
3
0
0
GB
HI guys

Does someone know how can I retrieve the size of a memory block that had been reserved using malloc/calloc?

Code:
char *chuck = (char*) malloc(sizeof(char) * 150);

Having declared the last statement how can I get back 150?

Thanks in advance.
 
You don't.
If you need to remember the size, then use another variable.

Also, casting the result of malloc in C is a bad thing.


--
 
>> Also, casting the result of malloc in C is a bad thing.

How is that a bad thing? From what I can see, he/she is assigning the memory space using malloc to a char pointer. perfectly fine there.

Regardless, he's probably right on having to memorize the size somewhere else.
 
Thanks for the advice.

Just to let you know the only function that I found related to this topics was malloc_size() which return the all size of the block you have reserved which include the housekeeping information(which as far as I could notice it varies its size) and therefore it is not useful for me.

Regards
 
More precisely: NO C standard library function to obtain allocated (by malloc) memory block size via pointer. May be any C implementations include such extented heap managementfunctions (it's true), but it's not a portable code, avoid this feature.

Sometimes it may be useful to design new codes (from the beginning) with user-defined memory allocator (kind of malloc wrapper). It's not a common way and as usually you can't use such wrappers with legacy codes.

No need to cast malloc returned pointer in C because of (void*) to (type*) conversion is legal in C (but not in C++;).
 
> How is that a bad thing?
Because casting suppresses a much more serious error you would otherwise get if you failed to include stdlib.h in the first place.

Since C quietly converts the void* returned by malloc into the char* of the assigned pointer, the cast at best does nothing.

If you're getting complaints about void* conversions, then stop using C++ to compile your code, or start using new/delete for memory management.

--
 
Well said Salem.
Too much C++ thinking in a C forum.
Check the archives:
We have gone round and round on this before.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top