M
Mark
Hello
given the very simple code:
#include <stdlib.h>
#include <stdio.h>
int g(void)
{
int i = 2;
return i;
}
int *f(void)
{
int *p;
p = malloc(sizeof *p);
/* skip result checking for the example's brevity */
*p = 2;
return p;
}
int main(void)
{
int i;
int *j;
i = g();
j = f();
printf("g()=%d, f()=%d\n", i, *j);
return 0;
}
Here is my reasoning.
In g() I declare automatic variable 'i' and initialize it with 2. The
storage, occupied by the variable, exists till the function returns. So we
can safely return the value. In function f() 'p' is as well automatic
variable, the value of which points to some storage, obtained by 'malloc()'
and this storage exists as long as the program runs. In main() local pointer
'j' is assigned to the returned value of g() and we can perfectly access the
value of that pointer.
Am I correct?
given the very simple code:
#include <stdlib.h>
#include <stdio.h>
int g(void)
{
int i = 2;
return i;
}
int *f(void)
{
int *p;
p = malloc(sizeof *p);
/* skip result checking for the example's brevity */
*p = 2;
return p;
}
int main(void)
{
int i;
int *j;
i = g();
j = f();
printf("g()=%d, f()=%d\n", i, *j);
return 0;
}
Here is my reasoning.
In g() I declare automatic variable 'i' and initialize it with 2. The
storage, occupied by the variable, exists till the function returns. So we
can safely return the value. In function f() 'p' is as well automatic
variable, the value of which points to some storage, obtained by 'malloc()'
and this storage exists as long as the program runs. In main() local pointer
'j' is assigned to the returned value of g() and we can perfectly access the
value of that pointer.
Am I correct?