Jump to content
  • Advertisement
Sign in to follow this  
gp343

Memory Leak, malloc and free explanation?

This topic is 3707 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!