Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » memory leak?

This thread is locked; no one can reply to it. rss feed Print
memory leak?
gering
Member #4,101
December 2003
avatar

does this produce memory leaks? if yes - what can i do? how can i free the memory and returning the string? ???

1char *strcat(char *s1, char *s2)
2{
3 int l1 = strlen(s1);
4 int l2 = strlen(s2);
5 int i;
6
7 // allocate enough memory
8 char *ret = (char*) malloc(l1+l2+1);
9
10 strcpy(ret, s1);
11 
12 do
13 {
14 ret[l1++] = s2<i>;
15 } while(s2[i++] != '\0');
16
17 return ret;
18}

__________________________________________________________
[ FreeGameDevLibs ]

Derezo
Member #1,666
April 2001
avatar

Technically yes. It's a memory leak.

For strcat() you shouldn't need to use malloc. Assume s1 is large enough to hold s2.

Otherwise use strncat(), which accepts an argument for the maximum length.

Oh, and just return a pointer to s1.

"He who controls the stuffing controls the Universe"

Ashteth
Member #3,310
March 2003
avatar

No this doesn't create a memory leak. What would create a memory leak is if function's caller failed to de-allocate the memory. Whenever you use new or malloc, the programmer is responsible for freeing the memory. The easiest way to deal with this potential problem is to place a comment at the beginning of the function stating that the function's caller is responsible for freeing memory. If you are using C++ you should consider returning a string object instead as this solution tends to address the memory allocation issue for you.

A simple comment like this is all that is needed to inform other programmers of the memory allocation issue. I.E.

// post: New char array allocated.
char* allocateMemory(void)
{
}

Derezo
Member #1,666
April 2001
avatar

If he's trying to replicate the standard strcat(), then this does create memory leaks. strcat() doesn't allocate any memory that needs to be later released with free().

In othe words, directly replacing strcat() in my own programs with the above version of strcat() will create memory leaks.

"He who controls the stuffing controls the Universe"

Ashteth
Member #3,310
March 2003
avatar

Yes it probably isn't a good idea, I actually replied before seeing your message and didn't think much about what was trying to be accomplished or why... By the way why would you want to do this or is it just an example?

Go to: