"K. Jennings" wrote:
>
We have the following:
typedef struct {
char *p ;
} data_structure ;
void f(data_structure *data)
{
char *r = malloc(16) ;
data->p = r ;
return ;
}
Assuming that malloc returns a non-NULL pointer, data->p will
point to a valid memory region for as long as data is not released. Is
this correct? I know that when f() returns the value of r becomes
undefined, but I assume that whatever it was pointing to will be left
untouched.
I believe you are getting confused because of previous posts which
included code along the lines of:
void f(data_structure *data)
{
char r[16];
data->p = r;
return;
}
In this case, you are left with data->p pointing to something that
no longer exists. (That is, r goes away upon return, yet data->p
still points to r.)
However, in your case, r is simply a pointer to the address returned
by malloc(). You are storing the _value_ of r into data->p, not its
address. The address returned by malloc() (assuming it succeeded)
is still valid until you free() it. The fact that r goes away is
irrelevent, as r was simply used to hold a value.
Consider that the body of your function could be written:
data->p = malloc(16);
The results are identical, and there is no "r" do disappear. (In
fact, a modern optimizing compiler may treat your code as if r did
not exist in the first place.)
--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody |
www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net |
www.fptech.com | <std_disclaimer.h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>