Standing on one foot (please translate to Hebrew):
When you ask for 16 bytes you actually get 20 (at least)
When you do ptr = malloc(16)
(size of allocated area) | Start of allocated area
unsigned int (or ...) | allocated area of 16 bytes
^
|--- ptrwhen you free at the middle, the size of allocated area cannot be found.
Check this for yourself by (beware dangerous idea): ptr=malloc(4*sizeof(int)); ptr--; ptr[0]=0xffffffff; ptr++; free(ptr);
As far as I recall - this will crush your program (and maybe the system... beware).
If you want to do it less harmfully:
ptr=malloc(4*sizeof(int));
ptr--;
printf("%x",ptr[0]);
ptr++;you should see 4 on screen (you might see something a bit bigger, because the allocation tries to keep from fragmantation and allocates stuff in chunks of several bytes).
-- Orr Dunkelman, [EMAIL PROTECTED]
"If it wasn't for C, we'd be writing programs in BASI, PASAL, and OBOL", anon
Spammers: http://vipe.technion.ac.il/~orrd/spam.html GPG fingerprint: C2D5 C6D6 9A24 9A95 C5B3 2023 6CAB 4A7C B73F D0AA (This key will never sign Emails, only other PGP keys.)
On Thu, 10 Mar 2005, Shlomi Fish wrote:
On Thursday 10 March 2005 14:20, Yoni wrote:On the same subject, can someone please explain a bit about the free() function ? what does it do, and how come you can only send it the memory address which you started allocating from ?
In ANSI C, you allocate a region of dynamically allocated memory using the malloc() function. This goes something like that:
<<< char * ptr_to_buffer; /* If I want a buffer with a size of 100,000 bytes */ ptr_to_buffer = malloc(100000); /* Do something with ptr_to_buffer */ . . . /* Free ptr_to_buffer so we won't have any memory leaks. */ free(ptr_to_buffer);
The purpose of the free() function is to release the allocated memory region and allow the application to make a future use of it. You need to pass it the beginning of the allocated region because of the way the algorithm works. Namely, it designates a region before the pointer returned as the allocated memory, to keep track of various control parameters for the allocated memory buffer, and to know how to later free it.
Regards,
Shlomi Fish
--------------------------------------------------------------------- Shlomi Fish [EMAIL PROTECTED] Homepage: http://www.shlomifish.org/
Knuth is not God! It took him two days to build the Roman Empire.
-------------------------------------------------------------------------- Haifa Linux Club Mailing List (http://www.haifux.org) To unsub send an empty message to [EMAIL PROTECTED]
-------------------------------------------------------------------------- Haifa Linux Club Mailing List (http://www.haifux.org) To unsub send an empty message to [EMAIL PROTECTED]
