Memory Leak, malloc and free explanation?

Started by
4 comments, last by Enigma 15 years, 11 months ago
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
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));
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.
Thanks All, for this.
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.
-Mike
Actually it should be:

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

Reason.

Σnigma

This topic is closed to new replies.

Advertisement