Search code examples
objective-ccocoa-touch

Returning an array (Warning: Function returns address of local variable)?


Returning an array (Warning: Function returns address of local variable) ?

interface

int* decimalConversion(int iX);

implementation

int* decimalConversion(int iX){
    int iMult[10] = {0,0,0,0,0,0,0};

    ...

    return iMult;  // <-- Warning: Function returns address of local variable
}

Solution

  • You should allocate space for the array. You're returning the address of an array that was created on the stack (hence local variable warning) if you're using C in that function use malloc(my_arr_size) if not use Objective-C's alloc.

    Example:

    int *my_arr = calloc(10, sizeof(int)); // Make sure we get zeroed memory
    // Fill array
    return my_arr; // Should no longer give a warning
    

    When done with it just use free(my_arr) same as release. Reason I did this in C is because I can see that you're returning an int* type and using C style declarations so if you're doing it in Objective-C let me know, and I can change my answer's example.

    The reason you are getting this error is because local arrays get put on the stack, when you return that array you return an address in a stack frame. The problem is that when that method finishes execution that stack frame is no longer valid and therefore you cannot expect any data that was on that frame to be valid (although there are cases when this does work, but it is considered bad practice). By allocating that array on the heap you can return a heap address where your data is assured to exist until you call free() on the pointer to that data.