I have written a simple C function to convert a string to an integer.
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.
char* inttostr(int num)
int i = 0;
int j = 0;
char *res = (char*)(malloc(10*sizeof(char)));
//take modulus of number and then divide it by 10
int rem = num%10;
num /= 10;
//the number is stores in the reverse order
buf[i++] = rem + '0';
//copy the characters in the right order
res[j++] = buf[i--];
res[j] = '\0';
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?