Visual Studio报错CRT detected that the application wrote to memory after end of heap buffer.

最近在调试代码的时候遇到这样一个错误: detected that the application wrote to memory after end of heap buffer,图示如下:

Visual Studio报错CRT detected that the application wrote to memory after end of heap buffer._第1张图片

报错代码块如下:

pResOut->text = (unsigned char *)malloc(strlen(enc_text));
memset(pResOut->text, 0, strlen(enc_text));
SM2_decrypt_with_recommended(enc_text, enc_len, pResOut->text, &pResOut->len, key);
...
free(pResOut->text);

报错原因是 enc_text 内存分配小了,在调用 SM2_decrypt_with_recommended 方法之后,现分配给 enc_text 的内存放不下赋给他的值,最终在回收内存的时候 free(pResOut->text) ,就会报上面的错误。

最终解决方法

解决办法就是给 pResOut->text 分配合适的内存空间,代码修改如下:

pResOut->text = (unsigned char *)malloc(enc_len);
memset(pResOut->text, 0, enc_len);
SM2_decrypt_with_recommended(enc_text, enc_len, pResOut->text, &pResOut->len, key);
...
free(pResOut->text);

这里的 enc_len 与要赋值给他的 enc_text 长度相等,再次运行代码问题解决,图示如下:

Visual Studio报错CRT detected that the application wrote to memory after end of heap buffer._第2张图片

到此问题解决。

你可能感兴趣的:(Visual,Studio,C语言加解密算法,C语言)