C ++ new & delete and functions

This is a little incomprehensible to me ... So, if I have a function:

char *test(int ran){ char *ret = new char[ran]; // process... return ret; } 

and then call it several 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, should I use delete[] for every call to new[] ?

+3
c ++ new-operator delete-operator
source share
3 answers

You don’t have to. But if you do not delete the memory that you reserved with the “new”, you will eventually start to run out of memory (memory leak).

+5
source share

Yes, yes, otherwise you will have a memory leak.

This is not the biggest idea to highlight in one function and free in another. Why not select in a for loop and pass a pointer to test - this holds new and delete together in the code.

+5
source share

The answer has already been asked, but since you marked the question as C ++, not C, this is how you probably want to do it in C ++ (of course, there may be other reasons not to do this, but there’s little chance).

 vector<char> (int ran){ vector<char> ret(char); // process... return ret; } 

And to call him:

 for(int i = 0; i < 100000000; i++){ vector<char> str = test(rand()%10000000+10000000); // process... } 

There are no new ones, therefore it is not deleted, therefore there is no memory leak.

Actually, you also probably want to use std :: string instead of char * (I used a vector to give a more general example).

Do not worry about the data to be backed up. The compiler optimizes it. Edit : okay, this may not optimize it :) however there are great chances. And until there are performance issues, go to the simplest version.

+3
source share

All Articles