所以,我需要一些帮助.我正在用 C++ 开发一个项目.但是,我认为我以某种方式设法破坏了我的堆.这是基于这样一个事实,即我向一个类添加了一个 std::string
并为它分配了另一个 std::string
的值:
So, I need some help. I am working on a project in C++. However, I think I have somehow managed to corrupt my heap. This is based on the fact that I added an std::string
to a class and assigning it a value from another std::string
:
std::string hello = "Hello, world.
";
/* exampleString = "Hello, world.
" would work fine. */
exampleString = hello;
因堆栈转储而在我的系统上崩溃.所以基本上我需要停止并检查我所有的代码和内存管理内容,然后找出我搞砸的地方.代码库仍然很小(大约 1000 行),所以这很容易做到.
crashes on my system with a stack dump. So basically I need to stop and go through all my code and memory management stuff and find out where I've screwed up. The codebase is still small (about 1000 lines), so this is easily do-able.
不过,我对这种东西很着迷,所以我想我会把它扔在那里.我在 Linux 系统上使用了 valgrind
,虽然不完全知道我在做什么,但它确实报告了 std::string
的析构函数是一个无效的自由.我不得不承认从 Google 搜索中得到了堆损坏"这个词;任何关于此类内容的通用文章也将不胜感激.
Still, I'm over my head with this kind of stuff, so I thought I'd throw it out there. I'm on a Linux system and have poked around with valgrind
, and while not knowing completely what I'm doing, it did report that the std::string
's destructor was an invalid free. I have to admit to getting the term 'Heap Corruption' from a Google search; any general purpose articles on this sort of stuff would be appreciated as well.
(在rm -rf ProjectDir
之前,在C#中再做一次:D)
(In before rm -rf ProjectDir
, do again in C# :D)
我没有说清楚,但我要求的是诊断这类记忆问题的建议.我知道 std::string 的东西是对的,所以这是我做过的事情(或者是一个错误,但 Select 没有问题).我敢肯定我可以检查我写的代码,你们非常聪明的人很快就会看到问题,但我想将这种代码分析添加到我的工具箱"中,就像这样.
I haven't made it clear, but what I'm asking for are ways an advice of diagnosing these sort of memory problems. I know the std::string stuff is right, so it's something I've done (or a bug, but there's Not A Problem With Select). I'm sure I could check the code I've written up and you very smart folks would see the problem in no time, but I want to add this kind of code analysis to my 'toolbox', as it were.
这些是可能解决问题的相对廉价的机制:
These are relatively cheap mechanisms for possibly solving the problem:
new[]
和 delete[]
,但您已经在这样做了.assert()
不够.没看过怎么知道呢?就像使用牙线一样,没有一个 assert()
在他们的代码中就足够了.为您的对象添加验证函数,并在方法开始和方法结束时调用该函数.auto_ptr
!那件事……令人惊讶;它的语义很奇怪.相反,选择Boost智能指针之一,或Loki 库之外的内容.new[]
and delete[]
, but you're already doing that.assert()
ing enough in your code. How do I know that without having seen it? Like flossing, no-one assert()
s enough in their code. Add in a validation function for your objects and call that on method start and method end.auto_ptr
! That thing is... surprising; its semantics are very odd. Instead, choose one of the Boost smart pointers, or something out of the Loki library.这篇关于内存管理、堆损坏和 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!