int * foo(int * in, int s)
{
int i;
int * out = (int *) malloc(s * sizeof(int));
for (i = 0; i < s; i++) a[i] = i;
return out;
}
int main()
{
int i;
int * a = malloc(10 * sizeof(int));
for (i = 0; i < 10; i++) out[i] = in[i];
// which of these two is correct?
// A
// int * b = foo(a, 10);
// B
// int * b = (int *) malloc(10 * sizeof(int));
// b = foo(a, 10)
return 0;
}
And most importantly! How do we free out in foo()?
In foo()? No. Since foo() is returning the pointer, you can't possibly free it there. The ownership changes to the caller, so that's who's supposed to free it.
Basically,
2nd question: I knew I shouldn't free in foo() because it makes no sense! Okay now I know where...
1st question: @ne555, yeah, it sort of slipped my mind that allocated memory remains allocated even when the pointer pointing to its starting address got destroyed, in this case, out. You see what vector did to me?
BUT! How does free(b) "know" how many elements to clear? (But then again I think this is is the case whenever free() is called)
Most implementations of malloc() write some information about the returned buffer a couple bytes before its start. free() uses this information to return the buffer to the heap.