Re: something unclear about "sizeof()" and "free()"
On 3 Okt., 11:36, shabbyOne <2009wangda...@gmail.com> wrote:
hello everyone
i am fresher, glad to "see" you .
pointer is very very hard to study, now i come accros a problem
like following:
a pointer is a address; what i do not know is whether a pointer
contains someting about its length implicitly. beacuse "sizeof()" and
"free()" functions behave different when i pass pointers to them.
for example :
char * p = (char*)malloc(100);
int num = sizeof(p); //num=4; sizeof()
does not the length of poniter p
free(p); //free()
function frees 100 byte ,it seems like that free() does
// know its
length of pointer p
i do not know why, i hope you can help me .
The sizeof operator (note: it isn't described in the
standard as a function) is actually also some compiler
magic, because it performs a compile-time evaluation
and no run-time evaluation. You could have used it
like this:
int sz = sizeof(int*); // returns the size of an int*
sz = sizeof(double); // returns the size of a double
sizeof is specified to return the number of bytes that
an object of the corresponding type would require
in memory, it *doesn't* specify the size of memory
that a pointer points to. What most beginners don't
understand (for obvious reasons) is that the argumnet
of sizeof may even by an expression, like in your example:
char* p;
....
sizeof(p);
In contrast to your expectations this form of application
does *not* evaluate the expression. The compiler only
checks which type this expression has - in this case the
expression "p" has the type "char*" - and simply returns
the size of this type. The result of sizeof is a so-called
integral constant expression and can therefore be used
when a size needs to be known during compile-time, e.g.
to declare an array or to define the value of an enumeration:
char* p;
enum E { e = sizeof(p) };
It is in fact so, that free() uses some form of "magic"
to get the information about the actually memory size
that needs to be freed again and there exists no public
API for a programmer to do that. You have to keep this
information either via different means (separate variable)
or the more recommended way would be to use data
structures that do that for you. A typical example is to
use std::vector<int> instead of an int-array that was
allocated via malloc.
i hope we can improve ourselves together
I hope that too.
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]