如何释放在C ++ DLL中分配的内存 [英] How to free allocated memory in C++ DLL

查看:484
本文介绍了如何释放在C ++ DLL中分配的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码加密C ++ DLL中的字符串

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?

感谢您的帮助。
Greets Heinz

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:


  1. 使用 free() - 这只会工作,如果他们使用相同的堆是很难保证。这是非常不可靠的,不是真的推荐。

  2. 引入一个内存管理接口(如 freeEncrypted()
  3. 使用 CoTaskMemAlloc()用于分配,并告诉调用者使用匹配的函数,例如 CoTaskMemFree()来释放内存。这与第2点类似,只是使用了一个众所周知的通用内存管理器。

  4. 更改接口,以便接受已分配数据的指针和其大小,以便调用者分配和释放

  1. tell the caller free the memory using free() - this will only work if they use the same heap which is hard to guarantee. This is very unreliable and not really recommended.
  2. introduce a memory management interface (such as freeEncrypted() function that is implemented in your library) and tell the caller use it - then memory will be returned to the right heap.
  3. use something well known like 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.
  4. change the interface such that it accepts pointer to already allocated data and its size so that the caller both allocates and frees the memory.

这篇关于如何释放在C ++ DLL中分配的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆