Search code examples
c++new-operatordelete-operator

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?


Solution

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