使用Valgrind进行泄漏检测和段错误定位

3

我正在检查代码中的内存泄漏问题。一切正常,直到我遇到了这段代码:

mSystem = new LightSystem();
sf::View *view = th::DisplayManager::Get()->GetCamera();
mSystem->SetView(*view);

SetView 的作用非常小(仅提取传递的 view 指针的一些成员)。 当最新的代码行被注释时,一切都正常,但是取消注释后,在默认模式下工作失败,并在使用 Valgrind 进行内存泄漏检测时出现错误(valgrind --tool=memcheck ./Binary)。

==23703== Use of uninitialised value of size 8
==23703==    at 0x6B8472: ltbl::LightSystem::SetView(sf::View const&) (LightSystem.cpp:55)
==23703==    by 0x6A7A7D: th::LightManager::Initialize() (LightManager.cpp:46)
==23703==    by 0x6A75EA: th::Root::Initialize() (Root.cpp:101)
==23703==    by 0x6A7113: th::Root::Root() (Root.cpp:66)
==23703==    by 0x6A7553: th::Root::Get() (Root.cpp:88)
==23703==    by 0x6291A8: th::Game::Initialize() (Game.cpp:36)
==23703==    by 0x61DC1C: main (main.cpp:82)
==23703== 
==23703== Invalid read of size 8
==23703==    at 0x6B8472: ltbl::LightSystem::SetView(sf::View const&) (LightSystem.cpp:55)
==23703==    by 0x6A7A7D: th::LightManager::Initialize() (LightManager.cpp:46)
==23703==    by 0x6A75EA: th::Root::Initialize() (Root.cpp:101)
==23703==    by 0x6A7113: th::Root::Root() (Root.cpp:66)
==23703==    by 0x6A7553: th::Root::Get() (Root.cpp:88)
==23703==    by 0x6291A8: th::Game::Initialize() (Game.cpp:36)
==23703==    by 0x61DC1C: main (main.cpp:82)
==23703==  Address 0x8 is not stack'd, malloc'd or (recently) free'd
==23703== 
==23703== 
==23703== Process terminating with default action of signal 11 (SIGSEGV)
==23703==  Access not within mapped region at address 0x8
==23703==    at 0x6B8472: ltbl::LightSystem::SetView(sf::View const&) (LightSystem.cpp:55)
==23703==    by 0x6A7A7D: th::LightManager::Initialize() (LightManager.cpp:46)
==23703==    by 0x6A75EA: th::Root::Initialize() (Root.cpp:101)
==23703==    by 0x6A7113: th::Root::Root() (Root.cpp:66)
==23703==    by 0x6A7553: th::Root::Get() (Root.cpp:88)
==23703==    by 0x6291A8: th::Game::Initialize() (Game.cpp:36)
==23703==    by 0x61DC1C: main (main.cpp:82)
==23703==  If you believe this happened as a result of a stack
==23703==  overflow in your program's main thread (unlikely but
==23703==  possible), you can try to increase the size of the
==23703==  main thread stack using the --main-stacksize= flag.
==23703==  The main thread stack size used in this run was 8388608.

问题是:为什么没有使用valgrind时可以成功执行,但使用后就出现错误。我已经尝试将--main-stacksize=设为较大的值,但这并没有帮助我解决问题。

3
如果没有使用valgrind,它可能无法“工作”。由于您正在使用无效指针,因此出现了未定义的行为,这意味着任何事情都可能发生。 - Charles Salvia
不要忘记,问题不一定与“mSystem->SetView(*view);”行有关。在那之前的任何时候,您可能已经在内存中损坏了任何地方。Valgrind 可能只是改变了事物的位置... - enobayram
1个回答

4
==23703== Process terminating with default action of signal 11 (SIGSEGV)
==23703==  Access not within mapped region at address 0x8

在某个时刻(可能是 LightSystem.cpp:55),您正在解引用一个指针,而您已将其分配为8,这看起来完全不像有效的地址。


好奇怪,我已经检查了所有指针(view之前和之后),一切似乎都没问题。 - Max Frai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接