AL-zami AL-zami - 1 year ago 68
C Question

what the the reason for the garbage value printed at the beginning

Here i am writing a program which will do two things

1.get a number between 0 to 10(10 is not included,so values should be less than 10),separate them and store them in an array

2.print the array for each number

For that purpose i wrote an if-else block which will initialize an array each time exactly according to the size of the current integer value which is denoted by variable called num

Meaning that if i have a number of single digit it will create an array of one element,If number is two digit long it will create an array of two element.But whenever i run the code i get some garbage value printed at the beginning

What might be the reason for that and how to solve this issue?

enter image description here

int mirror(int *arr,int num,int i);
int main(){

int num = 0;
int range = 1;
int *arr;
int i=0;

arr=(int *)malloc(range*sizeof(int));
arr=(int *)malloc(range*sizeof(int));

printf("%d ",arr[i]);


int mirror(int *arr,int num,int i){

if(num == 0){
return 0;
arr[i] = num%10;


Answer Source

It's because you're not setting arr[i] to anything in the base case in mirror function. And if there isn't any use of the return value of the function, why are you making it return anything?
Either make it void or if you've to return value from it, at-least make sure that all control paths return some value.

As suggested in the below comment by @JonathanLeffler:

void mirror(int *arr,int num,int i){
    arr[i] = num % 10;
    if (num >= 10)
        mirror(arr, num / 10, ++i);

And you're leaking memory horribly. Either free memory in each iteration or use a realloc and at the end of the program, free the memory.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download