Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing reported heap corruption when releasing native memory #7

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

drivehappy
Copy link

The Visual Studio debugger was reporting that there was heap corruption when attempting to call Marshal.FreeHGlobal. It appears that this uses a different heap than what the native side uses for allocation with malloc. To ensure that the same heap is used, a new export from zopfli.dll was added (ZopfliFree) to perform the companion free call - and the managed side now calls into this.

Since I couldn't find the original (assumed modified) sources for the zopfli.dll, I had to re-implement the ZopfliPNGExternalOptimize exported function as well to ensure the PNG compression still worked. For future reference, the implementations are:

int ZopfliPNGExternalOptimize(const unsigned char* datain, int datainsize, unsigned char** dataout) {
	ZopfliPNGOptions opts;

	const std::vector<unsigned char> origpng_cc(datain, datain + datainsize);
	std::vector<unsigned char> resultpng_cc;

	int ret = ZopfliPNGOptimize(origpng_cc, opts, false, &resultpng_cc);
	if (ret) {
		return ret;
	}

	int size = static_cast<int>(resultpng_cc.size());
	*dataout = (unsigned char*)malloc(resultpng_cc.size());
	if (!(*dataout)) {
		return ENOMEM;
	}

	memcpy(*dataout,
		reinterpret_cast<unsigned char*>(&resultpng_cc[0]),
		resultpng_cc.size());

	return size;
}

and,

void ZopfliFree(void* mem) {
	free(mem);
}

I used the Zopfli sources from the 1.0.2 release and I rebuilt the DLL binaries in Release under VS 15.7.1, and statically linked the runtime into it.

…m the wrong heap. Since we need access to 'free', a new export was created from the zopfli.dll to perform this cleanup from the same heap the memory was allocated from with 'malloc'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant