On 16 Mar 2006 01:33:57 -0800, "Ramki" <writerama@gmail.com> wrote in
comp.lang.c++:
[color=blue]
> How does free() , delete() works?
>
> If we allocate memory using the following statement
>
> int *p = malloc(100*sizeof(int));[/color]
....then we'll get a diagnostic from the compiler, since the code is
invalid. malloc() returns a pointer to void, and you cannot assign a
pointer to void to a pointer to another object type without a cast in
C++, although you can in C.
Also it is much better to use the type of the pointer rather than hard
coding the type of the object. If you are going to use malloc() in
C++, you should use it like this:
int *p = (int *)malloc(100 * sizeof *p);
The reason for the second change is to prevent errors that can occur
if you have to change the data type. Suppose for example you realize
that you need floating point values, and change p to be a pointer to
double. In your version you would need the change 'int' to 'double'
in two places, and create potential horrible problems if you changed
one but missed the other. In my version, you merely change "int *p"
to "double *p", and the sizeof value is automatically correct.
[color=blue]
> Inorder to release the memory we will call '"free(p) "
>
> How does it know about how many bytes/bits to be deleted?(same is the
> case with new and delete statements)[/color]
It may store it physically in the aura of the programmer, or write it
in the pattern of clouds in the sky. Such a detail is completely up
to the compiler and its library. The C++ language does not specify
the mechanism.
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://c-faq.com/
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html