使用 calloc 分配内存时出错(释放堆块 XXX 在释放后在 YYY 修改)

Error during memory allocation using calloc (Free Heap block XXX modified at YYY after it was freed)

我需要一系列 unsigned long long 类型的缓冲区,这些是我在分配中使用的代码行。

FAC_op_Buffer = static_cast<uint_64 *>( calloc(static_cast<uint_32>(ceil(static_cast<float>(2*FAC_N) / 64.0) ), sizeof(uint_64)) );
SDC_op_Buffer = static_cast<uint_64 *>( calloc(static_cast<uint_32>(ceil(static_cast<float>(2*SDC_n) / 64.0) ), sizeof(uint_64)) );

MSC_coder_h_lvl_1 = static_cast<uint_64 *>( calloc( static_cast<uint_32>(ceil(static_cast<float>(2*(MSC_n1_n2[0] + MSC_n1_n2[1])) / 64.0) ), sizeof(uint_64) ) );
MSC_coder_h_lvl_2 = static_cast<uint_64 *>( calloc( static_cast<uint_32>(ceil(static_cast<float>(2*(MSC_n1_n2[0] + MSC_n1_n2[1])) / 64.0) ), sizeof(uint_64) ) );
MSC_coder_h_lvl_3 = static_cast<uint_64 *>( calloc( static_cast<uint_32>(ceil(static_cast<float>(2*(MSC_n1_n2[0] + MSC_n1_n2[1])) / 64.0) ), sizeof(uint_64) ) );
MSC_coder_l_lvl_1 = static_cast<uint_64 *>( calloc( static_cast<uint_32>(ceil(static_cast<float>(2*(MSC_n1_n2[0] + MSC_n1_n2[1])) / 64.0) ), sizeof(uint_64) ) );
MSC_coder_l_lvl_2 = static_cast<uint_64 *>( calloc( static_cast<uint_32>(ceil(static_cast<float>(2*(MSC_n1_n2[0] + MSC_n1_n2[1])) / 64.0) ), sizeof(uint_64) ) );
MSC_coder_l_lvl_3 = static_cast<uint_64 *>( calloc( static_cast<uint_32>(ceil(static_cast<float>(2*(MSC_n1_n2[0] + MSC_n1_n2[1])) / 64.0) ), sizeof(uint_64) ) );

变量"MSC_n1_n2"、"FAC_N"、"SDC_N"包含要分配的位数。 uint_64 只是在 stdint 中找到的标准 int 的 typedef。

typedef uint64_t uint_64;

现在的问题是当它转到为 "MSC_coder_h_lvl_2" 分配的第二行时。我得到一个错误。 - Windows 触发断点......

堆:释放堆块 XXX 在释放后在 YYY 修改

内存位置XXX和YYY每次都在变化。但它总是指向我之前分配但未释放的另一个缓冲区。

如果我点击继续,其余的分配就会毫无问题地发生。当我查看内存 window 时,所有其他分配的位置都像预期的那样初始化为零。只有第二条语句失败,使 "MSC_coder_h_lvl_2" 指向 0x0000000.

我正在使用 calloc 而不是 new,因为我想要调整此缓冲区大小的功能。

谁能帮我解决这个问题。

"it always points to another buffer which I have allocated earlier but not freed"

我愿意相信您没有故意释放它。但根据经验,我相信 Visual C++ 胜过相信你。

验证这一点的一种快速方法是在一些可疑文件中 #define free(X)。当然,这是 100% 的内存泄漏,但是当错误消失后,您就会知道文件执行了不正确的 free 调用。

在我的代码中发现了问题。我非常愚蠢。与此冲突的较早缓冲区是问题所在。当我将数据写入该缓冲区时,我超出了它分配的大小。

由此linkhttp://c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=malloc#crash 问题 7.19 给了我一个想法来检查我是否超过了限制。 它说在分配后 space malloc 存储内部信息,如大小等。当我写的比我应该写的多时,我破坏了这些信息。

因此,当我分配一个不同的缓冲区时,它试图分配到这个已经使用过的块中,但我已经部分破坏了它的内部数据。

我纠正了这个超限问题,现在一切正常。