gpt4 book ai didi

c - 如何发现代码中的内存泄漏问题

转载 作者:行者123 更新时间:2023-11-30 16:12:07 25 4
gpt4 key购买 nike

我有内存泄漏问题,我怀疑问题可能出在下面的“base64_decode()”函数中。另外,请阅读代码中的注释。

uint8_t *unbase64_ct = NULL;
uint8_t *unbase64_sig = NULL;

int i = 0;

// ptr is just a buffer of fixed size containing encoded data
//separated with delim (i.e. "&" sign). The ptr may contain
//base64(ct)&base64(sig)& where base64(ct) is encoded ciphertext and
//base64(sig) is encoded signature of public key cryptography

char *next = NULL;
char *tokens = strtok_r(ptr, delim, &next);

do
{
if(i == 0)
{
int ln = strlen(tokens);
unbase64_ct = base64_decode((uint8_t*)tokens, (uint32_t*)&ln);
i++;
continue;
}

if(i == 1)
{
int ln = strlen(tokens);
unbase64_sig = base64_decode((uint8_t*)tokens, (uint32_t*)&ln);
i++;
continue;
}
}
while((tokens = strtok_r(NULL, delim, &next)) != NULL);

// I believe this function leaves leftovers.
uint8_t *base64_decode(uint8_t *bbuf, uint32_t *len)
{
uint8_t *ret;
uint32_t bin_len;

bin_len = (((strlen((char*)bbuf) + 3)/4) * 3);
ret = (uint8_t*)malloc(bin_len);

*len = EVP_DecodeBlock(ret, bbuf, strlen((char*)bbuf));
// Following good code practice, ret must be freed within the
//code block...
//However, how do i pass random number of bytes in the
//different way without using malloc?
return ret;
}

// I release here unbase64_ct and unbase64_sig as the output is
// dynamically allocated.

free(tokens);
free(unbase64_ct);
free(unbase64_sig);

它工作得很好,但是在多次运行整个代码(例如 1000 次)后,它会停止在 100 - 1000 范围内的随机值上。如何在没有动态内存分配的情况下重写 base64_decode 函数,或者发现内存泄漏问题我看不到?

最佳答案

每次调用base64_decode都会分配一个新的缓冲区,因此unbase64_ctunbase64_sig会被多次分配,但只释放一次。

关于c - 如何发现代码中的内存泄漏问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58401025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com