View Single Post
Old 23rd May 2019, 21:13   #1  |  Link
wonkey_monkey
Formerly davidh*****
 
wonkey_monkey's Avatar
 
Join Date: Jan 2004
Posts: 2,496
Trying to write a simple frame caching filter - need help with smart pointers, again

Here is a (simplified) snippet of code from a filter I'm writing to force frames to be cached by Avisynth:

Code:
FrameCache::FrameCache(PClip _child, IScriptEnvironment* env) : GenericVideoFilter(_child) {
	int i;

	cache = new PVideoFrame[end - start]; // cache is a private PVideoFrame*

	for (i = 0; i < vi.num_frames; i++) {
		cache[i] = child->GetFrame(i, env);
	}
}

FrameCache::~FrameCache() {
	int i;

	for (i = 0; i < vi.num_frames; i++) {
		cache[i - start] = NULL;
	}

	delete cache; // crashes here
}
The constructor creates an array of PVideoFrame and then populates it with pointers to every frame of the clip. This seems to work, as it keeps those frames live in Avisynth's cache and makes working with them much faster (for my particular purposes).

But the filter crashes when the destructor is called. My understanding was that by setting the PVideoFrame elements to NULL, I would release the hold on those frames, but calling delete on cache causes a crash.

Is this expected behaviour? I thought calling a delete on an array of NULL pointers should generally have no effect other than freeing up the memory for the array.

If I use malloc/free instead of new/delete there's no crash, but I'd like to understand what's going on instead of just trusting that to work.

No comments on what a terrible idea this might be, please It's for a very specific purpose and does its job perfectly (apart from the crash).
__________________
My AviSynth filters / I'm the Doctor
wonkey_monkey is offline   Reply With Quote