Which of the following is the correct way of doing it to avoid memory leaks?
//Option A
char* data = new char[4];
data = new char[5];
delete[] data;
//Option B
char* data = new char[4];
delete[] data;
data = new char[5];
delete[] data;
Which of the following is the correct way of doing it to avoid memory leaks?
//Option A
char* data = new char[4];
data = new char[5];
delete[] data;
//Option B
char* data = new char[4];
delete[] data;
data = new char[5];
delete[] data;
You have clear memory leak in option A. Let's say you have allocated memory for new char[4]; at some memory location 0x7256AC7D and data points to this location. Then without deleting this you have allocated another memory location for new char[5]; and data points to this new location. Now you have no pointer to old location 0x7256AC7D and have no way to delete that. So you are leaking that memory.
In other notes, it's better or easier to use std::shared_ptr or std::unique_ptr from C++11 to avoid this kind of leaks.