-
August 24th, 2009, 10:00 AM
#1
Memory Leak Problem!
Code:
char* get(char buffer[],int from, int until, int len)
{
int a = from;
int b = 0;
int end = from+until;
char *lol;
lol = new char[until+1];
while (a < len && a <= end) {
lol[b] = buffer[a];
a++;
b++;
}
lol[b] = '\0';
return lol;
}
That, as you can see, is causing a memory leak since i am using new.
The problem is i have no idea where to use delete.
-
August 24th, 2009, 10:15 AM
#2
Re: Memory Leak Problem!
After the return of the function.
Code:
char *myChar = get (... parameters);
... do something with myChar.
delete[] myChar;
-
August 24th, 2009, 10:23 AM
#3
Re: Memory Leak Problem!
oh i see, thanks!
-
August 24th, 2009, 10:33 AM
#4
Re: Memory Leak Problem!
Another problem:
What happens if you do
Code:
printf(get(...para's))
-
August 24th, 2009, 10:51 AM
#5
Re: Memory Leak Problem!
Originally Posted by HouseMD93
Another problem:
What happens if you do
Code:
printf(get(...para's))
A memory leak, and one you cannot fix making calls like that.
Why not drop using the memory allocation altogether, and return a std::string or even a container (i.e. vector<char>)?
Regards,
Paul McKenzie
-
August 24th, 2009, 10:55 AM
#6
Re: Memory Leak Problem!
Will it be ok if I use char instead of the pointer: char*?
Will that also cause a memory leak?
-
August 24th, 2009, 10:58 AM
#7
Re: Memory Leak Problem!
If you only want to return a single character, that'll work.
If you're interested in returning an entire string, then you have three basic options:
1) Allocate in the function and make sure you clean up after yourself.
2) Return a class type which automates cleanup internally. The most obvious such is std::string.
3) Make the output string a parameter so that no allocation is necessary. The downside here is that the caller needs to know how big to make the array.
-
August 24th, 2009, 10:59 AM
#8
Re: Memory Leak Problem!
Example:
Code:
#include <string>
std::string get(char buffer[],int from, int until, int len)
{
int end = from + until;
int maxChars = min(len, end);
return std::string(buffer + from, maxChars);
}
Not tested, but this should do the same thing as the code you have now, except that you are actually returning a string.
Regards,
Paul McKenzie
-
August 24th, 2009, 11:16 AM
#9
Re: Memory Leak Problem!
Ok thanks, although i have to rewrite every piece of code i have written. Atleast this way i won't get a memory leak.
-
August 24th, 2009, 11:38 AM
#10
Re: Memory Leak Problem!
It's probably better in the long run to rewrite using std::strings anyway.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|