Thread: Avoid memory leak

  1. #1
    Join Date
    Oct 2006

    Avoid memory leak

    I have written a simple C function to convert a string to an integer.

    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
    		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';
    	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?
    Last edited by lazyme; 04-09-2011 at 08:11 PM.

  2. #2
    Registered User
    Join Date
    Sep 2007
    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.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Toronto, Canada
    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.

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    New Zealand
    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.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Best way to avoid memory leak
    By mike_g in forum C Programming
    Replies: 15
    Last Post: 03-24-2008, 08:18 AM
  2. Replies: 2
    Last Post: 09-28-2006, 01:06 PM
  3. Replies: 6
    Last Post: 06-02-2006, 08:32 AM
  4. Memory leak or no?
    By rafe in forum C++ Programming
    Replies: 4
    Last Post: 10-02-2002, 04:33 PM
  5. How is this a Memory Leak?
    By Cheeze-It in forum C++ Programming
    Replies: 4
    Last Post: 05-24-2002, 04:59 AM

Tags for this Thread