I found a ZIP library that I want to re-write with WinAPI calls.
I have almost done it, but I can't allocate memory for a TState
structure.
state = new TState();
works fine!
state = (TState*)HeapAlloc(GetProcessHeap(), 0, sizeof(TState));
breaks archives!
If I change HeapAlloc()
to malloc()
, nothing changes!
So, what am I doing wrong?
CodePudding user response:
TState
contains some non-trivial members (namely: TTreeState ts
and TDeflateState ds
) that have their own constructors which are called properly by new
, but which are not called by malloc()
/HealAlloc()
. As such, you would need to use placement-new
to properly construct a TState
object inside of your allocated memory, eg:
buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(TState)); // or malloc()
state = new(buffer) TState;
...
state->~TState();
HeapFree(GetProcessHeap(), 0, buffer); // or free()
Otherwise, you will have to re-write TTreeState
and TDeflateState
to make them into trivial types (ie, remove their constructors). You will just have to initialize their data members manually after you have allocated each TState
instance.