About the number of elements in the c++ array

Asked 1 years ago, Updated 1 years ago, 34 views

Thank you for your help.

I'm not sure about the c++ array.
I wrote the code as follows.What
in the array with the following code? I thought I'd check if it contains a value.

#include<iostream>
constint N = 5;
main(){
    inti = 0, a[N];
    for(i=0;i<=N;i++){
        a[i] = i;
    }
    for(i=0;i<=N;i++){
        std::cout<<i<'<a[i]<'\n';    
    }
    std::cout<<'\n';
}

The results were then printed as follows.
0 0
11
22
33
44
55

*stack smashing detected*:./a.outterminated
Stop (Core Dump)

This a appears to contain {0,1,2,3,4,5} from the output results.
However, since the number of elements of a is 5, I think it is strange that 5 is included in a.
If you could tell me the reason why the strange value is included in a
Fortunately, I would also like to know why there is a cancellation (core dump).
Thank you for your cooperation.

c++

2022-09-30 19:44

1 Answers

Since the array has a loop of for(i=0;i<=N;i++), i has six values: 0,1,2,3,4,5.(In this case, it's moving to the point where the value is printed, so you've already noticed it.)

The sixth (index 5) is outside the allocated area, so the result is undefined, but crashing and spitting out a core dump is quite possible.

C/C++ array operations do not check that area, so it may appear that the sixth value is written.

It's not uncommon to be able to write or read because it's somewhere in the computer's memory, even if it's outside of the allocated space, but it's often used for other purposes, so if you rewrite outside of the space, the impact will appear later.

"Other uses" only affect that part when it is read.For example, if that part was used as an address, rewriting would point to a ridiculous address, which could lead to a CPU exception that could lead to a core dump.


2022-09-30 19:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.