C++ new & delete and functions
This is a bit unclear to me... So, if I have a function:
char *test(int ran){
开发者_如何转开发 char *ret = new char[ran];
// process...
return ret;
}
and then call it multiple times:
for(int i = 0; i < 100000000; i++){
char *str = test(rand()%10000000+10000000);
// process...
// delete[] str; // do i have to delete it here?
}
So the question is, do I have to use delete[]
for each new[]
call?
You don't have to. But if you don't delete memory you reserved with 'new' you will start running out of memory eventually (memory leak).
Yes you do, otherwise you'll have a memory leak.
It's not the greatest idea to allocate in one function and free in another, though. Why not allocate in the for loop and pass the pointer to test
-- this keeps the new
and delete
together in the code.
The answer was already given, but as you tagged the question as C++, and not as C, this is how you probably want to do it in C++ (of course, there might be other reasons not to, but there is little chance).
vector<char> (int ran){
vector<char> ret(char);
// process...
return ret;
}
And to call it:
for(int i = 0; i < 100000000; i++){
vector<char> str = test(rand()%10000000+10000000);
// process...
}
No new, thus no delete thus no memory leak.
Actually, you also probably want to use std::string instead of char* (I used vector to give a more general example).
Don't worry of data that will be copied. The compiler will optimize it out. Edit : ok, it might not optimize it out :) however there are big chances it will. And as long there is no performance issues, go for the simplest version.
精彩评论