C ++将指针递增到未知内存区域 [英] C++ Incrementing a pointer into unknown memory territory

查看:171
本文介绍了C ++将指针递增到未知内存区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于C / C ++处理盲目增加指针的行为的查询。

I have a query about the behavior of C/C++ dealing with blindly incrementing a pointer.

所以,我有一个指向int的指针作为参数函数

So, I have a pointer to an int as a parameter to a function

func(int * thePointer){...

我有一个循环里面的函数

and I have a loop inside that function

while(*thePointer) {
    ++thePointer;
}



我理解只要有 int 在内存中超出这个指针循环将继续,但如果内存属于另一种内存类型的部分呢?假设你增加到 double 的前4个字节。在这种情况下int将仍然有一个值/将循环继续吗?

I understand that as long as there are int's in the memory beyond this pointer the loop will continue, but what if the memory belongs to part of another memory type? Say you increment into the first 4 bytes of a double. Will the int still have a value/will the loop continue in this case?

免责声明:我知道这是很可能是坏的做法。这是一个纯粹的学术问题。

Disclaimer: I know this is very most likely bad practice. This is a purely academic question.

推荐答案

在内存中没有 int 强>。内存只是内存:字节的占位符。

In memory there is no such thing as a int or a double. Memory is just memory: placeholder for bytes.

因此,如果你继续增加一个指向 int 的指针,在内存中就是这样。如果你试图通过指针使用整个内存的那部分,你可能会把它的内容看作是一个 int

So, if you keep incrementing a pointer to int, you will point to the next four bytes in memory and that's it. If you attempt to use that portion of the memory through the pointer to integer, you will probably treat its content as if it were an int.

最后,您将指向内存中未分配给您的进程的区域,并且您的程序将以 SEGMENTATION FAULT 退出。

Eventually, you will point to a region of the memory not being assigned to your process and your program will exit with a SEGMENTATION FAULT.

这篇关于C ++将指针递增到未知内存区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆