i've got following code to encrypt a string in a C++ DLL
EXPORT WCHAR* EncryptString(WCHAR* stringToEncrypt) {
aes_context ctx;
WCHAR* in = stringToEncrypt;
WCHAR* out;
WCHAR* key = L"TestKey";
BYTE* buffEnc = (BYTE*)malloc(16);
BYTE* keyBuffEnc = (BYTE*)malloc(32);
memset(buffEnc, 0, 16);
memset(keyBuffEnc, 0, 32);
memcpy(buffEnc, in, wcslen(in) * 2);
memcpy(keyBuffEnc, key, wcslen(key) * 2);
aes_set_key(&ctx, keyBuffEnc, 256);
aes_encrypt(&ctx, buffEnc, buffEnc);
out = (WCHAR*)buffEnc;
// free(buffEnc);
// free(keyBuffEnc);
return out;
}
My problem is that i can not free the allocated memory because otherwise the result is broken. I wonder how can i free the used memory without losing the result? Have i to change the type of return value?
Thanks in advance for your help. Greets Heinz
This is indeed a problematic situation - you return a pointer to allocated memory and it's unclear who should free the memory. You have the following options:
free()
- this will only work if they use the same heap which is hard to guarantee. This is very unreliable and not really recommended.freeEncrypted()
function that is implemented in your library) and tell the caller use it - then memory will be returned to the right heap.CoTaskMemAlloc()
for allocation and tell the caller to use the matching function such as CoTaskMemFree()
for freeing memory. This is similar to point 2, just uses a well known common memory manager.Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments