English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

When you get heap memory with malloc, you have to use a size argument. To release the memory with free(), apparently you just use the pointer. Does this really release the memory from, say, a large structure pointer, and not just the first byte?

2007-01-14 21:49:00 · 2 answers · asked by Drew - Axeman 3 in Computers & Internet Programming & Design

Thanks Tony - that is what I was hoping for - I just didn't believe it was that simple.

2007-01-14 22:13:55 · update #1

2 answers

No, it doesn't need an argument. A good implementation will be able to recognize the block of memory being freed and the internal bookkeeping created during the malloc() will be used by free() to determine the size of the allocated block.

Yes, when you free a pointer, you're implicitly freeing ALL of the memory that you allocated when you malloc()'ed and received that pointer.

You should only be free()'ing pointers that were returned by malloc().

2007-01-14 21:58:28 · answer #1 · answered by tony1athome 5 · 2 0

If you go into the implementation, when you call x = malloc(1000) you get a pointer to 1000 free bytes. Actually, the system allocates more than 1000 bytes. At the fromt of this, location x - (something), there is a memory structure that the OS uses for bookkeeping. When you free(x) the OS retrieves that structure, so it knows how much memory is allocated at x.

2007-01-15 06:35:29 · answer #2 · answered by sofarsogood 5 · 3 0

fedest.com, questions and answers