memory allocation query

E

ed

Hello,

Is there a way to return the amount of memory which has been allocated
to a malloc()'d pointer? Or is this not possible?
 
E

Eric Sosman

ed said:
Hello,

Is there a way to return the amount of memory which has been allocated
to a malloc()'d pointer? Or is this not possible?

This is Question 7.27 in the comp.lang.c Frequently
Asked Questions (FAQ) list at <http://c-faq.com/>.
 
J

Joe Smith

"Eric Sosman" ...
This is Question 7.27 in the comp.lang.c Frequently
Asked Questions (FAQ) list at <http://c-faq.com/>.
But if you've malloced it, isn't the answer to this question sitting in your
source? I don't really get the use of the adverb 'unfortunately' here. Joe
 
E

Eric Sosman

Joe Smith wrote On 05/02/06 17:40,:
"Eric Sosman" ...


But if you've malloced it, isn't the answer to this question sitting in your
source? I don't really get the use of the adverb 'unfortunately' here. Joe

Yes, the program knew the memory size when it called
malloc(). The "unfortunate" thing is that the program quite
often doesn't bother to remember what it once knew, or even
if it remembers it mightn't bother to tell other parts of
the program what it knows.

gets() is, of course, the horrible example. It would
be nice if gets() could somehow discover the size of the
buffer it was given, but a pointer doesn't communicate that
information. Even if it did, the troubles would not be
over; consider

struct {
char buff[100];
int this;
double that;
unsigned int flags;
} *object;
object = malloc(sizeof *object); // assume success
gets (object->buff);

If gets() could query the size of the memory block to which
its argument pointed, it would presumably get the size of
the entire struct rather than just the `buff' element ...
Learning the raw size of a piece of memory may not be useful
unless you also know something about the context.

At the end of the day it's the programmer's job to see
to it that memory blocks are properly sized, and to make the
sizes available where they're needed. C's simplicity incurs
costs; languages with fancier memory management don't so much
eliminate the costs as redistribute them. You pays your money
and you takes your choice.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,150
Latest member
MakersCBDReviews
Top