How to manage memory in function, which returns dynamically allocated variable? What happens with buffer, when function returns?
char * getStr(){
char * buffer = new char[12];
sprintf_s(buffer, 12 , "abcdef");
return buffer;
}
How to manage memory in function, which returns dynamically allocated variable? What happens with buffer, when function returns?
char * getStr(){
char * buffer = new char[12];
sprintf_s(buffer, 12 , "abcdef");
return buffer;
}
buffer
stays allocated, but luckily you're returning the pointer.
You must delete[]
that pointer at some point, else you'll leak memory.
Notice how I've used []
: that's important. This balances your allocation of an array of char
s. (Conceptually the runtime stores the length of an array allocated with new something[]
, and delete[]
informs the runtime to free the correct number of elements.)
When function returns, your buffer still exists. There is nothing like embedded memory manager, you MUST free all the memory you allocated manualy. That is about C.
In C++ standart library, there is objects called smart pointers. With the pressence of exceptions, they are totally recommended to use. There is fine answer on SO about them: What is a smart pointer and when should I use one?
Nothing.
The address which is stored in *buffer
will be returned to the caller and it is up to the caller to delete
the memory again.
buffer
is a pointer that means it addresses a point in memory.
new
will allocate a bloc of memory, for the command new char[12]
it will allocate 12 char
s worth of memory.
new
returns the address of the memory and that is assigned to your pointer buffer
.
Note that because you only have a pointer to the memory, you need to clean that up before buffer
goes out of scope. If the address contained in buffer buffer
goes out of scope you will have "leaked" memory. Because it cannot be reclaimed. You clean up the memory allocated by new char[12]
with the command: delete[]
.
Thank to Bathsheba for his answer.
My vision of a solution to the problem:
char * getStr(){
char * buffer = new char[12];
sprintf_s(buffer, 12 , "abcdef");
return buffer;
}
int _tmain(int argc, _TCHAR* argv[]){
char * p = getStr();
std::cout << p << std::endl;
delete[] p;
return 0;
}