Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I passing array ownership back to caller from my library function?

I came to C from Python. Python has a delightfully simplistic white glove approach to manipulating strings. The more I use arrays in C, the more I think how convenient it would be to have certain features. Rather than writing loops to do this every time I need to do a particular operation, I have decided to create a library to do this.

So, let's say I have a library and the call looks something like this:

char* new_array = meatSlicer(old_array, element_start);

I'm passing the pointer to the array I want changed, expecting a pointer return, and indicating what element to slice at.

If meatSlicer (yes, I'm a sucker for bad naming) returns a pointer to an array that is made locally within the slicer, the pointer will be a bad pointer. So, within meatSlicer() I have this:

    ... manipulation before the below ...

    char *heap_the_Array;     /* put it on the heap to pass it back to caller */
    heap_the_Array = malloc((size + 1) * sizeof(char));

    int i;                
    for (i = 0; i <= (size + 1); i++){           /* make it so... again */

            heap_the_Array[i] = newArray[i];     /* newArray is the local */

    }

    return heap_the_Array;                       /* return pointer */

My question is, am I properly returning ownership to the caller function so that it can free() the new array? Is passing a pointer to an array on the heap sufficient for that?

like image 414
d0rmLife Avatar asked Jan 27 '26 04:01

d0rmLife


1 Answers

Yes, copying local variables into malloc-ed regions of memory works well. You can replace the loop with a call of memcpy to reduce the code size. Write

memcpy(heap_the_Array, newArray, size+1);

instead of

int i;                
for (i = 0; i <= (size + 1); i++){           /* make it so... again */
        heap_the_Array[i] = newArray[i];     /* newArray is the local */
}
like image 175
Sergey Kalinichenko Avatar answered Jan 29 '26 20:01

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!