ARM体系结构中的指针处理和Valgrind方法

Pointer Handling and Valgrind approach in ARM architecture

本文关键字:Valgrind 方法 处理 指针 体系结构 ARM      更新时间:2023-10-16

我正在ARM目标上运行以下代码。以下是观察结果1) 尽管在未初始化的情况下访问指针,但代码执行时没有出现任何问题/崩溃(HalloWorldMain*hm1)2) Valgrind在这个程序中没有抱怨任何内存问题。

==344== Memcheck, a memory error detector
==344== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==344== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info
==344== Command: ./HalloWorld
==344==
Hallo World!
Prinitng at simpleTest
==344==
==344== HEAP SUMMARY:
==344==     in use at exit: 0 bytes in 0 blocks
==344==   total heap usage: 2 allocs, 2 frees, 8,552 bytes allocated
==344==
==344== All heap blocks were freed -- no leaks are possible
==344==
==344== For counts of detected and suppressed errors, rerun with: -v
==344== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
#include <iostream>
#include "HalloWorldMain.h"
#include <fstream>
using namespace std;
HalloWorldMain::HalloWorldMain() {
    // TODO Auto-generated constructor stub
    ofstream file;
    file.open("1.txt", ios::out);
    file << "Inside the file n";
}
void HalloWorldMain::simpleTest()
{
    cout<<"Prinitng at simpleTestn";
}
HalloWorldMain::~HalloWorldMain() {
    // TODO Auto-generated destructor stub
}
int main()
{
    HalloWorldMain hm;
    HalloWorldMain *hm1;
    cout << "Hallo World!n";
    hm1->simpleTest();
}

有人能帮我理解这种行为吗。感谢

当您调用对象的成员函数时,对象的地址将作为隐式参数移交给该函数。在您的情况下,用于调用函数的指针未初始化,因此地址是垃圾。

但这在您的情况下没有问题,因为simpleTest()没有以任何方式访问对象。它也可以是一个静态函数。但是,一旦您尝试访问成员变量,程序就会崩溃。

程序运行正常的原因是因为HalloWorldMain::simpleTest不访问HalloWorldMainthis指针。换句话说,simpleTest可以被定义为静态的,因为它并没有利用类的内部状态。

另一种方法是,在C++中,所有非虚拟类函数都将this指针作为显式的第一个参数,但在所有其他方面都与任何正常的C或C++函数类似。由于在您的情况下,您从未使用this指针来访问对象的内部状态,因此程序的行为与预期的一样。

如果将simpleTest设为虚拟的,则会发生崩溃,因为需要查询存储在对象中的vTable。

这可能是C++中未定义的行为,但正如我在所知的所有平台上所解释的那样。