Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ทำไมการเข้าถึง array out of bounds ใน C++ ไม่ให้ error


เพราะ C++ ไม่ทำ bounds checking (ตรวจสอบขอบเขต array) ภาษาอื่นอย่าง Java, Python ทำ bounds checking โยน exception/error

แนวคิดการออกแบบ C++: ไม่ควรช้ากว่า C และ C ไม่ทำ array bounds checking

หากเข้าถึง out-of-bounds: Undefined Behavior (UB) ตามมาตรฐาน C++ อะไรก็ได้: crash, freeze, ทำงานปกติ (เหมือนปกติ), ชน memory อื่น, security vulnerability

แก้ไข: ใช้ std::vector หรือ std::array พร้อม .at() ที่ทำ bounds checking และโยน std::out_of_range exception