I was asked these questions in a interview.
- Why exactly Binary code and Data was separated i.e why did they plan for Data segment why not everything inside code segment?
2.
class A
{
private :
int i;
public:
void show()
{
printf("hello");
}
};
int main()
{
A* a = NULL; (what happens in object table?)
A* aa = new A(); (what happens in object table?)
a->show();
aa->show();
delete aa;
return 0;
}
How exactly aa and a are different and how exactly object behaves inside memory.
code segment vs data segment
code segment is read-only, while data segment is read/write, if you mix these 2 sections together, update the data while keep the code secure becomes a challenge: one example is as Lol4t0 pointed out:
and also, code segment are usually load into memory pages which are readonly (VirtualAlloc(PAGE_READONLY))
a(null) vs aa (non-null)
a and aa themselves are simply stack variable of type A*, but a points to NULL, while aa points to an object allocated in heap.
a->show() is translated into:
because no member variable is referenced in show(), this should works fine.
aa->show() is translated into:
here aa is a valid address, so even if you reference member variable in show(), it would work.
Notice unlike virtual functions, which is resolved in runtime thus require a vptr in each object, member functions are just normal functions which take the this as first parameter, and resolved by compiler in compile time.