C ++ new & delete and string & functions

It’s good that the previous question was answered, but I found another problem.

What to do, if:

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

And then run it:

 for(int i = 0; i < 100000000; i++){ string str = test(rand()%10000000+10000000); // process... // no need to delete str anymore? string destructor does it for me here? } 

So, after converting a char * string to a string, I no longer need to worry about deleting?

Edit: As I said, I have to delete[] call each new[] , but in my case this is not possible since the pointer is lost, so the question is: how to convert char to the correct string?

+6
c ++ string new-operator char delete-operator
source share
5 answers

Here you do not convert char* to [std::]string , but copy char* to [std::]string .

As a rule, for each new should be delete .

In this case, you will need to save a copy of the pointer and delete when you are done:

 char* temp = test(rand()%10000000+10000000); string str = temp; delete[] temp; 
+9
source share

It seems that you are under the pretext that passing char* to std :: string transfers ownership of the allocated memory. Actually it just makes a copy.

The easiest way to solve this problem is to simply use std :: string throughout the function and return it directly.

 std::string test(int ran){ std::string ret; ret.resize(ran - 1); // If accessing by individual character, or not if using the entire string at once. // process... (omit adding the null terminator) return ret; } 
+3
source share

Yes Yes Yes.

If you are using linux / os x, look at something like valgrind that can help you with memory problems

You can change your test function so that it returns string instead of char * , so you can delete [] ret in the test function.

OR you could just use the string in the test, and also not worry about the new / delete.

+2
source share

You must call delete for each new , otherwise you will be memory leaks. In the case you showed, you discard the pointer, if you must leave the function as returning char* , then you will need to use two lines to create std::string to save a copy of char* until delete .

A better solution would be to rewrite your test() function to directly return std::string .

+2
source share

You need to do something like this:

 for(int i = 0; i < 100000000; i++){ int length = rand()%10000000+10000000; char* tmp = test(length); string str(tmp); delete[length] tmp; } 

This correctly removes the highlighted char -array.

By the way, you should always end with zero on a line if you create it this way (i.e. inside the test function), otherwise some functions can easily get confused and process the data behind your line as part of this, which in the best case your application crashes, and in the worst case, an excessive buffer overflow leading to undefined behavior at a later point, which is the ultimate nightmare for debugging ...;)

+2
source share

All Articles