I have written a simple C function to convert a string to an integer.
Code:
char* inttostr(int num)
{
char buf[10];
int i = 0;
int j = 0;
char *res = (char*)(malloc(10*sizeof(char)));
//take modulus of number and then divide it by 10
while(num)
{
int rem = num%10;
num /= 10;
//the number is stores in the reverse order
buf[i++] = rem + '0';
}
i--;
//copy the characters in the right order
while(i>=0)
res[j++] = buf[i--];
res[j] = '\0';
return res;
}
However, I notice that I have allocated memory for the char arr res and havent freed it. I can not free it inside this function as I am returning this to my calling function.
How can I avoid such a memory leak? Should I allocate the res array in the caller function and free it there? Or is there any other better approach?