Char Array Is Getting Corrupted Topic is solved

If you are using the main C++ distribution of wxWidgets, Feel free to ask any question related to wxWidgets development here. This means questions regarding to C++ and wxWidgets, not compile problems.
alys666
Super wx Problem Solver
Super wx Problem Solver
Posts: 329
Joined: Tue Oct 18, 2016 2:31 pm

Re: Char Array Is Getting Corrupted

Post by alys666 »

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 call

Code: Select all

delete[] objectData;
in the constructor to prevent memory leaks:

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;
}
in constructor this code is excessive(see below)...because object data is not allocated, you are still constructing the object.
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;
	}
there is no leak, in your old code, if you never set new data to the buffer, but only once in constructor.
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.
ubuntu 20.04, wxWidgets 3.2.1
Kvaz1r
Super wx Problem Solver
Super wx Problem Solver
Posts: 357
Joined: Tue Jun 07, 2016 1:07 pm

Re: Char Array Is Getting Corrupted

Post by Kvaz1r »

alys666 wrote: Mon Jun 24, 2019 10:59 am If it somehow saves wrong code from crashing, it's not a reason to use it.
programmer must write correct code, using simplest data structures.
It's exactly a reason. Standard container is always more shorter, reliable and readable. But of course you can use std::array<> instead if your data won't change size.
Post Reply