C ++:写入/从无效的读/出界数组索引吗? [英] C++: Write to/read from invalid/out of bound array index?

查看:124
本文介绍了C ++:写入/从无效的读/出界数组索引吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我是一个初学者,当谈到C ++编程。昨天我遇到过一些比较奇怪。我试图通过向它指向一个指针确定数组的长度。由于的的sizeof 的没有工作,我做了一些谷歌搜索,结束了这个网站上,我找到了答案,这是不可能的。相反,我应该把一个出界值的数组的最后一个索引,直到达到该指数递增计数器。因为我没有要覆盖载的最后一个索引的信息,我试图把出界值一个索引的最后一个接一个。我预期失败,但由于某种原因,它没有。

First of all, I am a beginner when it comes to C++ programming. Yesterday I encountered something rather strange. I was trying to determine the length of an array via a pointer pointing towards it. Since sizeof didn't work I did a little Google search and ended up on this website where I found the answer that it was not possible. Instead I should put an out of bound value at the last index of the array and increment a counter until this index is reached. Because I didn't want to overwrite the information that was contained at the last index, I tried putting the out of bound value one index after the last one. I expected it to fail, but for some reason it didn't.

我以为我犯了一个错误别的地方,该阵列较长那么我指定它是,所以我做了如下试验:

I thought that I made a mistake somewhere else and that the array was longer then I assigned it to be, so I made the following test:

int a[4];
a[20] = 42;
std::cout << a[20];

的输出是42没有任何错误。为什么这项工作?这不应该是有效的,对不对?什么是更有趣的是,这适用于任何原始类型数组的事实。但是,一旦我用一个std :: string的节目即刻与1存在。

The output is 42 without any errors. Why does this work? This should not be valid at all, right? What's even more interesting is the fact that this works with any primitive type array. However, once I use a std::string the program instantly exists with 1.

任何想法?

推荐答案

您的系统正好没有使用,只是碰巧是内存中 20 * sizeof的(INT)从数组的地址字节进一步。 (从它的开始。)或者内存属于你的过程,因此你可以惹它,要么碰坏为自己或只是机缘巧合休息罢了。

Your system just happens to not be using the memory that just happens to be 20 * sizeof(int) bytes further from the address of your array. (From the beginning of it.) Or the memory belongs to your process and therefore you can mess with it and either break something for yourself or just by lucky coincidence break nothing.

底线,不要做:)

这篇关于C ++:写入/从无效的读/出界数组索引吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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