using unallocated memory without error?

前端 未结 5 1566
礼貌的吻别
礼貌的吻别 2020-12-06 18:37

Why does that work?

#include 
using namespace std;

int main() {
    float* tab[3];

    int i = 0;
    while(i < 3) {
        tab[i] = ne         


        
5条回答
  •  离开以前
    2020-12-06 18:42

    Both of them do out-of-bounds array access - you have an array of 3 float pointers, and you're accessing the 8th array. This is bound to crash.

    However, unlike Java or some other managed languages, there is no explicit bounds checking for each array access (since the performance cost of that is prohibitive). So the only bounds checking you have is your MMU. If you end up accessing memory that does not belong to your application, you'll crash. If you hit memory that is not allocated but still happens to be part of your process (could be a guard word, for example), it'll silently succeed. This is a great recipe for very-hard-to-track-down bugs.

    Bounds checking is key. Do it whenever you can.

提交回复
热议问题