I am actually bothered about how dynamic memory allocation is actually working in this code.
Read first Modern C or some other good book about C
then see this C reference. Late, read for example some C17 draft standard, e.g. n2176. It is specifying the behavior of malloc(3). Read also more about the call stack, automatic variables, and C dynamic memory allocation.
This approach is new to me as I couldn't find any resource that could explain this code.
Consider studying the source code of GNU libc. It is implementing malloc
(on Linux, above syscalls(2) such as mmap(2)...)
And read also a good operating system textbook. You might understand how malloc
works on ordinary OSes. It is related to virtual address space since sometimes malloc
is growing that space.
Read of course the documentation of your C compiler (e.g. GCC). Enable all warnings and debug info, so use gcc -Wall -Wextra -g
. Then read the documentation of your debugger (e.g. GDB) and run your program step by step under your debugger.
BTW, your code is wrong: both malloc(3) and scanf(3) could fail, and you don't check that.
At last, take inspiration from existing open source software coded in C, like GNU bash or GNU bison or GPP or GTK.
C and C++ are different programming languages
Your question mentions C++. C and C++ are very different. For C++, read first a good C++ programming book. Then see this C++ reference. Later, take inspiration from existing C++ open source software, such as fish, Qt, FLTK, RefPerSys and many others on github.
Consider using static source code analyzer tools
Such as Frama-C, the Clang static analyzer, and in 2021 perhaps Bismon.