Is it possible to both return and free a dynamically allocated array?
int *mycopy(int *from, int len)
{
int i;
int *to;
to = malloc(len*sizeof(int));
for(i = 0; i < len; ++i) {
to[i] = from[i]
}
return to;
// how do I free the "to" array?
// do i even need to, or does the array only have function scope
// and get deleted when the function exits?
}
Or is
void mycopy(int *from, int *to, int len);
my only option?
The mycopy function is just a simple example but in the real code I want to nest them such as calling it like
a = mycopy(mycopy(b, 5), 5)
How do I do this without allocating more memory every time the function is called? Thanks.
If you return the array, the calling code must take responsibility for freeing it (and the function must not free it). If you don't return the array, the function must free it, but then the function is pointless anyway. So, the function will not be freeing the array.
If you use:
void mycopy(int *from, int *to, int len);
the calling code must do the memory allocation. If you use:
void mycopy(int *from, int **to, int len);
the function can do the allocation — but it still must not free it.
But the initial function is better: it is fine as written. You can call it like this:
int b[] = { 1, 2, 3, 9, 2 };
int *a = mycopy(b, sizeof(b)/sizeof(b[0]));
...use a...
free(a);
Incidentally, you cannot afford to nest calls to your copy function — or, at least, you can't afford to do it using this:
a = mycopy(mycopy(b, 5), 5);
It would leak memory horribly. If you must do nested calls (why?), then you'd need:
int *c;
int *a = mycopy((c = mycopy(b, 5)), 5);
But it would be cleaner and tidier to write:
int *a = mycopy(b, 5);
int *c = mycopy(b, 5);
That is less error prone, easier to understand, and uses slightly fewer characters to boot!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With