AL-zami AL-zami - 1 month ago 5
C Question

What is the reason for the garbage value printed at the beginning?

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, but if the number is two digits long, it will create an array of two elements, etc. 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

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int mirror(int *arr,int num,int i);
int main(){

int num = 0;
int range = 1;
int *arr;
while(num<10){
int i=0;
if(num<(int)pow(10,range)){

arr=(int *)malloc(range*sizeof(int));
}else{
range+=1;
arr=(int *)malloc(range*sizeof(int));
}

mirror(arr,num,i);
for(i=range-1;i>=0;i--){
printf("%d ",arr[i]);
}
printf("\n");
num++;
}

}

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

if(num == 0){
return 0;
}
arr[i] = num%10;
mirror(arr,num/10,++i);

}

Answer

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.