检测到堆损坏,在哪里可以删除动态内存?
我不断收到此错误,但我不知道何时可以删除变量的动态内存:upSizedPlaintext、upsizedKey、upsizedCiphertext 或 upsizedKeyD?
由于我这样做是为了作业,所以我必须使用 BOOST 测试,并且在讲师将使用的测试中,他将删除加密文本并在 BOOST 测试中解密。但我无法找到在哪里可以删除上面的变量。非常感谢任何想法和帮助?
另外,我必须使用 C 风格的字符串而不是 C++ 字符串。
I keep getting this error but I can't figure out when I can delete the dynamic memory for the variables: upSizedPlaintext, upsizedKey, upsizedCiphertext, or upsizedKeyD?
Since I am doing this for an assignment, I have to use BOOST tests and in the test that the lecturer will use, he will delete encryptedText and decrypted in the BOOST test. But I can't manage to find out where I can delete the variables from above. Any ideas and any help is greatly appreciated?
Also, I HAVE to use C-style strings not C++ strings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您从加密和解密返回指向新内存的指针时,调用这些函数的代码将负责在它们接收的指针上调用
delete[]
。这不是一个很好的接口,也是我们喜欢在 C++ 代码中使用 std::string 的原因之一!
C 代码中堆损坏的常见根源是忘记字符串的 nul 终止符并分配
strlen(s)
字节而不是strlen(s) + 1
字节。我相信你在很多地方都会这样做。As you are returning pointers to new memory from encrypt and decrypt, the code calling those functions becomes responsible for calling
delete[]
on the pointers they receive.Not a very good interface, and one reason why we like to use std::string in C++ code!
The usual source of heap corruption in C code is to forget the nul terminator for strings and allocate
strlen(s)
bytes instead ofstrlen(s) + 1
bytes. I believe you do that in several places.在我看来,同样的问题
应该
在不同的地方都有同样的问题。堆损坏并不是因为您在错误的时间进行了删除,而是因为您在分配的内存范围之外进行了写入。在这种情况下,因为您分配的字节太少。
Looks like the same problem to me
should be
Same issue in various places. Heap corruption is not because you are deleting at the wrong time, it's because you are writing outside of the bounds of allocated memory. In this case because you are allocating one too few bytes.
您可以在任何可见的地方删除这些变量。由于它们是函数内的局部变量,因此您可以在该函数内的任何位置或将这些变量作为指针传递到的任何函数中删除它们。
在哪里可以删除这些指针指向的内存和在哪里应该删除这些变量之间有很大的区别。有很多地方不应该删除它们。在传递变量的函数中删除它们通常是一个坏主意。在函数使用完它们之前删除它们是一个非常非常糟糕的主意。
您应该在上次使用和创建它们的函数返回之间的某个时间删除它们。如果您根本不删除它们,则会出现内存泄漏,如果太早删除它们,则会出现未定义的行为。
You are able to delete those variables anywhere they are visible. Since they are local variables inside a function, you can delete them anywhere inside that function, or in any function to which you pass those variables as pointers.
There's a big difference between where you can delete the memory pointed to by those pointers and where should delete those variables. There are lots of places where you shouldn't delete them. Deleting them in a function to which the variable is being passed is typically a bad idea. Deleting them before the function is finished using them is a very, very bad idea.
You should delete them somewhere between the last use and the return from the function that created them. If you don't delete them at all you have a memory leak, and if you delete them too early you have undefined behavior.