Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a pointer after returning its value inside a function

I have this function:

char* ReadBlock(fstream& stream, int size) {     char* memblock;     memblock = new char[size];     stream.read(memblock, size);     return(memblock); } 

The function is called every time I have to read bytes from a file. I think it allocates new memory every time I use it but how can I free the memory once I have processed the data inside the array? Can I do it from outside the function? Processing data by allocating big blocks gives better performance than allocating and deleting small blocks of data?

Thank you very much for your help!

like image 369
Emer Avatar asked Jun 30 '10 00:06

Emer


People also ask

How do you delete a pointer variable in C++?

delete and free() in C++ In C++, the delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.

Can a pointer be returned from a function?

We can pass pointers to the function as well as return pointer from a function. But it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns.

Does deleting a pointer delete the object?

The only thing that ever gets deleted is the object *test , which is identical to the object *test2 (since the pointers are the same), and so you must only delete it once.


2 Answers

Dynamic arrays are freed using delete[]:

char* block = ReadBlock(...); // ... do stuff delete[] block; 

Ideally however you don't use manual memory management here:

std::vector<char> ReadBlock(std::fstream& stream, int size) {     std::vector<char> memblock(size);     stream.read(&memblock[0], size);     return memblock; } 
like image 140
Georg Fritzsche Avatar answered Sep 17 '22 13:09

Georg Fritzsche


Just delete[] the return value from this function when you've finished with it. It doesn't matter that you're deleting it from outside. Just don't delete it before you finish using it.

like image 21
sigfpe Avatar answered Sep 17 '22 13:09

sigfpe