Interesting behavior with dynamically allocated array

瘦欲@ 提交于 2019-12-13 04:42:16

问题


So I'm working with a dynamically allocated array, and I've set it to hold 5 elements, which should thus be 0-4. I made a function to reserve it if necessary, but I wanted to see if I was getting the program crash I expected when I assigned a value to the array at [5]. But, no error, not until [6].

Here's my code:

int* dynamic_arr;
dynamic_arr = new int[5];

for(int i = 0; i <= 100; i++){
    dynamic_arr[i] = i;
    used++;
    cout << dynamic_arr[i]<<endl;
}

Here's the output:

0 //i[0]
1 //i[1]
2 //i[2]
3 //i[3]
4 //i[4]
5 //i[5]  <-- should be out of range

After that it crashes.

Why am I able to assign a value to a portion of the array that is, well, out of range for lack of a better term?

Thanks

OpSrcFTW

EDIT: Appreciate the answers guys, thanks. I'll read more before posting for a quick answer next time, sorry.


回答1:


Accessing beyond the end of an array produces undefined behavior. It does not necessarily produce a crash. Anything can happen.




回答2:


Accessing the array beyond its bounds is undefined behaviour. Anything could happen, it need not be repeatable, and there is little point trying to "understand" any patterns you think might be there.




回答3:


Accessing beyond the size of the array will produce undefined behavior. Undefined behavior includes things like your code crashing, working as perfectly fine, working on one computer and not another, restarting your computer or destroying the whole universe.




回答4:


As others have already pointed out, you have undefined behavior, so while a crash is possible, the code can also appear to work.

In a case like yours, appearing to work when you access slightly past the end of the memory you allocated is fairly common. The code that manages the memory for the free store will often round your request size up to the next size it finds convenient, such as a power of two. As such, it's not particularly rare to have at least a little memory past the end of what you requested that you can write to without an visible problems.

You cannot, of course, count on that though -- not even with the same compiler using the same flags, etc. Just for example, the standard library could decide how to act based on the amount of memory available on the target machine, using more padding to optimize speed when there's plenty of RAM available, and less padding to reduce memory usage when there's less available.

As such, no you can't depend on a crash at any particular point -- but this also isn't a place you can get by with testing or thinking it's something you only need to worry about if you're going to port the code.



来源:https://stackoverflow.com/questions/14969609/interesting-behavior-with-dynamically-allocated-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!