in constructor this code is excessive(see below)...because object data is not allocated, you are still constructing the object.Deluge wrote: ↑Mon Jun 24, 2019 6:35 pm
I think that is what the user over in cplusplus.com forums is trying to tell me, that I need to callin the constructor to prevent memory leaks:Code: Select all
delete[] objectData;
Code: Select all
ResourceObject::ResourceObject(unsigned char* data, unsigned int data_size) { if (objectData) { delete[] objectData; objectData = NULL; objectSize = 0; } objectData = new unsigned char[data_size]; memcpy(objectData, data, data_size); objectSize = data_size; }
you need this code, if you have separate function - set_data(like in mine example ) -so you can set new data many times for the same buffer. then obviously you must deallocate the previous one. also not NULL, but nullptr.
Code: Select all
if (objectData) {
delete[] objectData;
objectData = NULL;
objectSize = 0;
}
also you must somehow protect your class, if <data> given as parameter to constructor is null.
- will you create real buffer with zero length, and some size.
- or you will not allocate a buffer, and set objectData to nullptr.
there is only question where are you getting initial data pointer(passed to constructor), and how that data was deallocated, because you stored a copy of that data in your buffer...
pointer is just an address of memory region, if you allocated this area on heap, you must somehow deallocate it(return it to free memory pool of heap manager). it's your responsibility. else you will have a memory leak.