Sign in to follow this  

Memory Leak, malloc and free explanation?

This topic is 3487 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi All, I've written the below code which will turn a C-style lower case character string into upper case character strings. My question here is that, won't the below code result into memory leak - as free(tmp) is not present? I alway read that each malloc must have a corresponding free function in order to avoid memory leaks. Can someone please elaborate on this memory leak thing?

TCHAR* ToUpper(TCHAR *s)
{
  TCHAR  *p;
  TCHAR *tmp = (TCHAR*)malloc(_tcslen(s) * sizeof(TCHAR*));
  memset(tmp, 0, _tcslen(s));
  wcscpy(tmp, s);

  for (p = tmp; *p != '\0'; p++)
  {
    *p = (TCHAR) _toupper(*p);
  }

  return tmp;

}

int main()
{
	TCHAR* strTest = TEXT("microsoft");
	strTest = ToUpper(strTest);
	return 0;
}	


Thanks, Jr

Share this post


Link to post
Share on other sites
In this case, since you malloc tmp and then return it, the calling function will have to free the returned tchar array, or else it will leak.

Also, I haven't used malloc in years, but shouldn't that be:

TCHAR *tmp = (TCHAR*)malloc(_tcslen(s) * sizeof(TCHAR));

Share this post


Link to post
Share on other sites
It seems to me, you first allocate enough tmp memory on the heap to fit your upper case string in and you return the actual tmp pointer. In your main function, you call it once, so there is an extra string allocated on the heap and returned into strTest. But as you never free this space, you will have a memory leak (altough your operating system will clean everything up after your program ended). So if you do not want this memory leak, you should call free(strTest) somewhere aftwer you are finnished using the upper case string strTest.

Share this post


Link to post
Share on other sites
Quote:
Original post by Driv3MeFar
In this case, since you malloc tmp and then return it, the calling function will have to free the returned tchar array, or else it will leak.

Also, I haven't used malloc in years, but shouldn't that be:

TCHAR *tmp = (TCHAR*)malloc(_tcslen(s) * sizeof(TCHAR));


Actually it should be:

TCHAR *tmp = (TCHAR*)malloc((_tcslen(s) + 1) * sizeof(TCHAR));

otherwise you'll corrupt the heap because you didn't allocate room for the null terminator.

Share this post


Link to post
Share on other sites

This topic is 3487 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this