C++ new & delete and functions

一世执手 提交于 2019-12-10 19:17:38

问题


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?


回答1:


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).




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2965927/c-new-delete-and-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!