1) Casting pointer to incompatible type invokes undefined behavior. Your program has no obligations to work as you expect. It might even format your hard drive and this will be behavior allowed by standard.
2) size of int and size of my_malloc are not equal. You are trying to access memory you do not own: another undefined behavior here.
In your case you are probably writing on stack which is instantly rewritten.
What is the cause for this problem and how can it be corrected? |
Do npt do thing not allowed by language.
Yes, we can cast between compatible types.
void*
and
char*
are compatible with everything, but you cast from them to types incompatible with
real type of underlying object is undefined too.
If you do something else and it works, it does not. It
seems to work. Any change to the source code, enviroment or compiler can break it.
Also: you do not need to write struct everywhere in C++.
my_malloc* mal = (my_malloc *)p;
is valid and preferred c++.
You do not have to return anything from main. It returns 0 automaticaly.
Do not use c-casts. They are dangerous. Use c++ casts which would tell about illegality of your actions even before you run your program.