OSDev.org
https://forum.osdev.org/

C++ Variable and an Error
https://forum.osdev.org/viewtopic.php?f=1&t=11672
Page 1 of 1

Author:  Tolga [ Tue May 30, 2006 11:06 pm ]
Post subject:  C++ Variable and an Error

Hi. I'm writing my kernel with C++. (GCC) I wrote a simple video class for text mode. When i am write my code same this:

//------------- C++ ---------------
tvideo video;

int main()
{
video.clear();
}

//----------------------------------

My kernel is halting.

But when i am write it same this, it is working.

//------------ C++ ----------------
int main()
{
tvideo video;
video.clear();
}
//---------------------------------

What is the matter? Why it is halting? I tried in bochs, on real pc and wmvare.

Author:  Colonel Kernel [ Tue May 30, 2006 11:16 pm ]
Post subject:  Re:C++ Variable and an Error

What have you done to ensure that static constructors are being called before main() is run? As the implementor of the OS, such C++ run-time support is your responsibility to implement.

This might help.

Author:  Candy [ Wed May 31, 2006 9:37 am ]
Post subject:  Re:C++ Variable and an Error

Tolga wrote:
Hi. I'm writing my kernel with C++. (GCC) I wrote a simple video class for text mode. When i am write my code same this:

//------------- C++ ---------------
tvideo video;

int main()
{
video.clear();
}

//----------------------------------

My kernel is halting.

But when i am write it same this, it is working.

//------------ C++ ----------------
int main()
{
tvideo video;
video.clear();
}
//---------------------------------

What is the matter? Why it is halting? I tried in bochs, on real pc and wmvare.


As quoted above, you need to call the constructor before you call anything (specifically: that dereferences the this-pointer at some time) on the given object. When the object is on the stack, the constructor call is added to the start of the function and the object is on the stack (destructor at end, etc). When it's a global object, its constructor can't be added to "the global function" since it doesn't exist. Instead, the global function is emulated by the startup code (crt0.o) by calling all functions in .ctors and upon exit, calling all functions in .dtors. These are sections in your executable (or something similar). Your code doesn't call these constructors, whereafter the object itself contains garbage or zeroes (depending on whether you zero the memory or not) and any information in the garbage/zeroes might cause any type of behaviour, including crashes. In some cases it might go completely unnoticed, although the C++ standard doesn't require this. I know that GCC does not explicitly check the "this"-pointer.

Long story short, call all constructors in .ctors and see it work just the same.

Page 1 of 1 All times are UTC - 6 hours
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/