
non-local pointers to c(m)alloc'ed arrays
Quote:
> Here is a simplified version of what I want to do:
> int main()
> {
> int n, s, a, *sum;
> sum=sumfn(&n, &s, &a);
> .
> .
> .
> }
> int *sumfn(int *sn, int *ss, int *sa)
> {
> int *j=calloc(sn*ss+sa, sizeof(int));
> .
> .
> .
> return (j);
> }
> Since I'm not using alloca'd memory nor am I free'ing the memory, I can
> effectively transfer the array to main() merely by returning its address to
> a pointer in main(). I'm fairly certain this is legal although I would like
> confirmation just in case.
Yes, it's legal, but be careful how you think about this. "Transfer to"
doesn't mean anything here. calloc returns a pointer to memory allocated
from the free store. You use the value contained in that pointer to
access the memory. If you copy that value somewhere else you can use the
copied value as well as the original value. In particular:
void use(int *iptr)
{
*iptr = 3;
Quote:
}
int main()
{
int *ip = calloc(1, sizeof(int));
use(ip);
printf("%d\n", *ip);
free(ip);
return 0;
Quote:
}
If you think of what's happening here in terms of transferring memory
you'll be lost: the memory allocated by calloc gets transferred to the
function use but it never comes back. That's not right: use can use the
memory, and main can use the memory. It doesn't belong to any one
function. Instead, think of which functions have pointers to this
memory. Any function with a pointer to this memory can use it.