C++指针输出从0到242的内存地址并停止
C++ pointer output memory address from 0 to 242 and stops
我在下面代码中的目标是查看内存地址是否确实由于p++而发生了变化(确实如此),但我不明白为什么程序会停止(但没有终止)以显示超过I=242的内存地址?换句话说,超过242行,程序什么也不做,最后一行"就这样"永远不会执行。
感谢
#include <iostream>
using namespace std;
int main()
{
cout<<"start..."<<endl;
int x=100;
int *p = &x;
for (int i=0; i<300; i++)
{
cout<<i<<". &p:="<<p<<" v:="<<*p<<endl;
p++;
}
cout << "that's it!" << endl;
return 0;
}
结果:
start...
0. &p:=0x7fff59c30c34 v:=100
1. &p:=0x7fff59c30c38 v:=1706885214
2. &p:=0x7fff59c30c3c v:=32767
3. &p:=0x7fff59c30c40 v:=1505954904
。.
240. &p:=0x7fff59c30ff4 v:=946024503
241. &p:=0x7fff59c30ff8 v:=892744247
242. &p:=0x7fff59c30ffc v:=13617
int x=100;
int *p = &x; //you allocated one int and you can point to it
for (int i=0; i<300; i++)
{
cout<<i<<". &p:="<<p<<" v:="<<*p<<endl;
p++;
// ^^^
// here you are pointing your pointer at next 4 bytes, but
// dereferencing it is an undefined behavior that you actually do observe
// you don't know what is next address pointing to and you are not allowed
// to dereference it
}
正如我在评论中所说,这是未定义的,可能会顺利进行100年,然后停止进行。
您的测试解决方案可能是:
int *p = new int[300]; //now you can point to any address within this table
for (int i=0; i<300; i++)
{
cout<<i<<". &p:="<<p<<" v:="<<*p<<endl;
p++;
}
使用p++,您正试图访问一些未分配给程序的内存。我想242只是一个任意的数字,你的操作系统会停止你的尝试。这并不完全正确,也不会前后一致。
您的程序在多个帐户上有未定义的行为。
int x=100; int *p = &x;
到目前为止还不错。这允许你做*p(得到100)和++p,将指针设置为一个过去的x。
不允许取消引用该指针。也不允许进一步增加。指针数学在从[0]到最后一个数组的范围内是合法的,将单个对象计算为[1]数组。
底线是在第一次迭代之后,任何事情都可能发生。
OS将内存页映射到大小为1k、4k、8k等的进程
指针p指向映射的"页面"中的地址,一旦指针p指向的地址超出映射的页面,内核就会知道您正在重新定义无效内存,因此会发出信号。
当直接运行程序而不是在cmd中运行时。一切都很好。(即使我循环3000次)
然后我在cmd控制台中运行它时被冻结了。
所以我想这主要是因为程序和cmd shell可能共享内存,从而导致冻结。
所以它确实依赖于操作系统。
相关文章:
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 在C++中打印指向不同基元数据类型的指针的内存地址
- CUDA:统一内存和指针地址的更改
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 使用内存地址访问结构的属性值
- 如何读取特定地址的进程内存?
- 为什么C++总是显示十六进制内存地址,而不仅仅是整数?
- 如果 const 不分配内存,为什么我可以获取 const 的地址?
- 将布局映射到内存地址
- 为什么同一个变量的内存地址不同?
- LLVM 传递以在特定地址分配内存
- 无法将内存地址转换为值
- 是否可以仅通过将分配的指针地址存储在C++中来分析内存?
- 给定特定内存地址的数组的动态内存分配
- 在 Microsoft Access SQL 中调用自定义 DLL 函数时传递的内存地址无效
- 我有一个线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x8)错误.我认为这是由于内存管理不好.我可以
- 获取 R 数据帧的内存地址
- 如何配置bazel以运行地址/内存清理器?
- 存储 std::list 元素的地址;内存
- 确定库的地址内存