Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 234
Kristen Martinson Avatar asked Dec 16 '22 11:12

Kristen Martinson


1 Answers

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 obj-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 Obj-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.

like image 181
Jesus Ramos Avatar answered Feb 15 '23 11:02

Jesus Ramos