> -----Original Message-----
> From: dev...@li...
> [mailto:dev...@li...] On Behalf
> Of J Miller
> Sent: Thursday, May 16, 2002 4:03 AM
> To: Dev-C++ Users (E-mail)
> Subject: [Dev-C++] Generic C++ question.
>
>
> Hi all,
>
> If a method returns a char pointer (char*).
>
> If the above method does a malloc() to allocate memory
> for some text (or something) and then fills that memory.
>
> The char* is returned to the user code.
>
> Who (or which code) is responsible for doing a free() on the char*?
>
> John M'
In C++ DO NOT USE malloc()/free(). malloc()/free() do not call the
objects' constructors and destructors. In C++ use only new, delete,
new[] and delete[].
The caller of the function is responsible to clear the memory returned
by the called function, if it allocated memory on the free store.
E.g.:
char *something()
{
char *p=new char[100];
for(int i=0; i<100; i++)
p[i]='a';
return p;
}
int main()
{
char *ptr=something();
// play with ptr
delete[] ptr;
}
In C++ avoid programming in such low level. Use the standard library
containers instead which supress any need for explicit resource
allocation and deallocation. For example:
#include <vector>
const std::vector<char> something()
{
using std::vector;
vector<char>p(100);
for(vector<char>::size_type i=0; i<p.size(); i++)
p[i]='a';
return p;
}
int main()
{
using namespace std;
vector<char>array=something();
// play with array
// array is destroyed automatically, all its contents
// are cleared, element desttructors are called. No possibility
// for memory leak (and in general for ANY resource leak!)
}
If you find that the vector<char> return of something() is expensive,
you can pass the "array" vector to something() by reference and fill it
there.
In summary, try to use C++ as a high level language and not as low level
one. There is much to gain from that. Unfortunately it usually is
teached and used in low level style (usually by C programmers since C++
is very newly "official" language, it got standardised just in 1998).
Ioannis
* Ioannis Vranos
* Programming pages: http://www.noicys.cjb.net
* Alternative URL: http://run.to/noicys
|