C++ new[] into base class pointer crash on array access

前端 未结 5 739
南笙
南笙 2020-12-21 10:24

When I allocate a single object, this code works fine. When I try to add array syntax, it segfaults. Why is this? My goal here is to hide from the outside world the fact

5条回答
  •  旧巷少年郎
    2020-12-21 10:57

    Each instance of B contains Both X data member and the "vptr" (pointer to the virtual table).

    Each instance of A contain only the "vptr"

    Thus , sizeof(a) != sizeof(b).

    Now when you do this thing : "S = new b[10]" you lay on the memory 10 instances of b in a raw , S (which has the type of a*) is getting the beginning that raw of data.

    in C::m() method , you tell the compiler to iterate over an array of "a" (because s has the type of a*) , BUT , s is actualy pointing to an array of "b". So when you call s[i] what the compiler actualy do is "s + i * sizeof(a)" , the compiler jumps in units of "a" instead of units of "b" and since a and b doesn't have the same size , you get a lot of mambojumbo.

提交回复
热议问题