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!
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.
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.
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.
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; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With