ARM体系结构中的指针处理和Valgrind方法
Pointer Handling and Valgrind approach in ARM architecture
我正在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
不访问HalloWorldMain
的this
指针。换句话说,simpleTest
可以被定义为静态的,因为它并没有利用类的内部状态。
另一种方法是,在C++中,所有非虚拟类函数都将this
指针作为显式的第一个参数,但在所有其他方面都与任何正常的C或C++函数类似。由于在您的情况下,您从未使用this
指针来访问对象的内部状态,因此程序的行为与预期的一样。
如果将simpleTest
设为虚拟的,则会发生崩溃,因为需要查询存储在对象中的vTable。
这可能是C++中未定义的行为,但正如我在所知的所有平台上所解释的那样。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- valgrind-hellgrind与泄漏检查的结果不同
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 寻找一种在运行时检测 valgrind/memcheck 的方法,而无需包含 valgrind 标头
- Valgrind:getter方法中包含rdlock的线程加载冲突
- ARM体系结构中的指针处理和Valgrind方法