Re: How does free() know how many bytes to free???



MAx wrote:
Hi,
A call to free() is used to de allocate memory which has been
allocated by a malloc()
or a calloc() call.
How does free() know how many bytes to deallocate?

The size is stored in bytes just before the useful area. Note that additional bits are used for other purposes.

Here's a small (32 bit!) program to show:

#include <stdlib.h>
#include <stdio.h>

void
all(size_t s)
{
unsigned char *ucp;
int i;

ucp = malloc(s);
printf("%#x:", s);
for (i = 0; i < 8; i++)
printf(" %02x", ucp[i-8]);
printf("\n");
}

int
main(int argc, char *argv)
{
all(0x1234);
all(0x12340);
all(0x123400);
}

--
These are my personal views and not those of Fujitsu Siemens Computers!
Josef Möllers (Pinguinpfleger bei FSC)
If failure had no penalty success would not be a prize (T. Pratchett)
Company Details: http://www.fujitsu-siemens.com/imprint.html

.



Relevant Pages

  • Re: 2D array of structures
    ... programming habits. ... int str_len; ... // Declaring of menu items, necessary for later reuse in array ... // it's time to allocate memory on the fly, ...
    (comp.lang.c)
  • Problem in compiling a C code with MSVC++6.00
    ... When I save the file as a cpp file, it compiles and runs ... int p1; ... void checkfile; ... printf("cannot allocate memory for elements!"); ...
    (comp.lang.c)
  • Re: Basic Pointer Question...
    ... I coded a function to allocate memory and i am passing a pointer to the function. ... In addition, as malloc() is hidden within a function, freecan be easily forgotten. ...
    (comp.lang.c)
  • Re: I am sorry for this...
    ... > int main ... > is it legal or does the temporary get destroyed at the 'f's closing brace? ... introduced to allocate memory for the result of a function for the ... return path the function returns a valid reference, while in another, ...
    (comp.lang.cpp)
  • SetBkMode Transparent takes no effekt
    ... i'm developing a program to print out some richtext with pictures. ... public int FormatRange(bool measureOnly, PrintPageEventArgs e, int charFrom, ... Marshal.StructureToPtr(fr, lParam, false); ...
    (microsoft.public.win32.programmer.gdi)