Question

i have started writing some code in C but I m rather new to that language. I have a long long number and want to convert it to an int array. After doing some research i have created the following function:

long long* convertNumberToArray(long long* number, int* length){

    *length = trunc(log10(*number))+1;

    long long num_array[*length];
    int i=*length-1;
    while(*number!=0)
    {
         //when this line is added it works! 
        //printf("fun: modulo: %lld", *number%10);       
        num_array[i] = *number%10;        
        *number = truncl(*number/10);         
        i--;
    }

    long long* return_array = num_array;     

    return return_array;
}

The weird thing is that if i run it as it is, and for example give the following number 123456 i get the following output from main:

main: 1
main: 2
main: 3
main: 4
main: 5059987506418679813
main: 5473089784

when i add the commented line

printf("fun: modulo: %lld", *number%10)

the result is correct and as expected:

main: 1
main: 2
main: 3
main: 4
main: 5
main: 6

I cannot understand this behavior and why it works when the above line is inserted. Any hint or help will be appreciated.

Thanks in advance, Dina

Was it helpful?

Solution

The problem is that you've created num_array as a local within convertNumberToArray() and later you return the address of that variable -- once you return from convertNumberToArray() all of its locals are no longer valid. What happens when you do this is undefined. When you see the correct results, you've just gotten lucky; none of the data is safe though. You must never (ever ever ever...) return the address of a local variable expecting the data it points at to remain in tact.

To solve this correctly, create the array to return data to within main() and pass it to the function as a new parameter. An alternative is to use malloc() (or any other allocation function) to create the buffer on the heap within convertNumberToArray() but if you do this, you must also write code to return the memory later (or you will cause a memory leak).

OTHER TIPS

Basically, you return a pointer to a temporary array. Once the function exits, this array is no longer allocated on the stack, and can be overwritten. When it actually is overwritten however depends on what you do next, but you can not rely on it staying in the stack regardless of what you do.

A safe way to return an array would be to allocate it on the heap via malloc. However, you should later free it when it's no longer needed, or it will occupy its portion of memory for the rest of the program's execution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top