Freeing Space in Array-Returning Fonction

Hello everyone!

I have a serious issue:

I only recently noticed this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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()?
Last edited on
You don't free inside foo(). You free in main (¿why?)
By the way, it is error prone, so c++ provides constructor and destructors.

About the other question, make a diagram. Analyse the content of the pointer and the pointed memory.
A.

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,
1
2
3
b=foo(/*...*/);
//...
free(b);
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)
Last edited on
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.
Topic archived. No new replies allowed.