C++指针输出从0到242的内存地址并停止

C++ pointer output memory address from 0 to 242 and stops

本文关键字:地址 内存 输出 指针 C++      更新时间:2023-10-16

我在下面代码中的目标是查看内存地址是否确实由于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可能共享内存,从而导致冻结。

所以它确实依赖于操作系统。