doubt about freeing memory

O

orium69

Hi everyone!

I have a doubt, when I free an alloced memory, how does the compiler
know how many bytes I have alloced forward the pointer.

eg:

int *coiso;

coiso=(int *)malloc(sizeof(int)*10);

free(coiso);

How the compiler know that it has to free from coiso to
coiso+(sizeof(int)*10)?

thanks

sorry for my probably realy bad english...
 
A

Andrey Tarasevich

eg:

int *coiso;

coiso=(int *)malloc(sizeof(int)*10);

Casting the result of 'malloc' is not a good idea. Why don't you just do

coiso = malloc(sizeof(int)*10);

An even better idea would be doing

coiso = malloc(10 * sizeof *coiso);
free(coiso);

How the compiler know that it has to free from coiso to
coiso+(sizeof(int)*10)?

Short answer: somehow.

This is an implementation detail, which you are not supposed to worry about. For
example, the run-time library might store the size originally passed to 'malloc'
somewhere in a secret place. 'free' might know how to retrieve that size when
necessary.
 
I

Ian Collins

Hi everyone!

I have a doubt, when I free an alloced memory, how does the compiler
know how many bytes I have alloced forward the pointer.

eg:

int *coiso;

coiso=(int *)malloc(sizeof(int)*10);

free(coiso);

How the compiler know that it has to free from coiso to
coiso+(sizeof(int)*10)?
It isn't the compilers problem, it is the underlying implementation of
the memory allocator that keeps track of allocated block sizes.
 
K

Keith Thompson

I have a doubt, when I free an alloced memory, how does the compiler
know how many bytes I have alloced forward the pointer.

eg:

int *coiso;

coiso=(int *)malloc(sizeof(int)*10);

free(coiso);

How the compiler know that it has to free from coiso to
coiso+(sizeof(int)*10)?

This is question 7.26 in the comp.lang.c FAQ,
<http://www.c-faq.com/malloc/freesize.html>.

See also questions 7.7 and 7.7b. While you're at it, you might read
all of section 7, and the rest of the FAQ as well. It's a very good
resource.
 

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,754
Messages
2,569,522
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top