-
Avoid memory leak
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?
-
That's not a leak. It'd be a leak if you lost a pointer to the allocated memory. You simply need to document that the caller is responsible for freeing the memory (much the way the POSIX strdup() works).
Alternatively, yes, you could require that the caller allocate memory. It's really up to you. Neither way is better than the other.
-
Since the function accepts an integer, perhaps the better solution is to return an integer. You can construct the result likewise to what you have but just sum in x1, x10, x100 etc the digits as you accumulate them. No need to deal with malloc'ing char arrays.
-
I would suggest that you allow the caller to pass in a buffer of sufficient size so that the whole idea of memory allocation becomes the caller's responsibility.
Afterall, that's what Itoa does.