I can use more memory than how much I’ve allocated with malloc(), why?

You’ve asked a very good question and maybe this will whet your appetite about operating systems. Already you know you’ve managed to achieve something with this code that you wouldn’t ordinarily expect to do. So you would never do this in code you want to make portable.

To be more specific, and this depends entirely on your operating system and CPU architecture, the operating system allocates “pages” of memory to your program – typically this can be in the order of 4 kilobytes. The operating system is the guardian of pages and will immediately terminate any program that attempts to access a page it has not been assigned.

malloc, on the other hand, is not an operating system function but a C library call. It can be implemented in many ways. It is likely that your call to malloc resulted in a page request from the operating system. Then malloc would have decided to give you a pointer to a single byte inside that page. When you wrote to the memory from the location you were given you were just writing in a “page” that the operating system had granted your program, and thus the operating system will not see any wrong doing.

The real problems, of course, will begin when you continue to call malloc to assign more memory. It will eventually return pointers to the locations you just wrote over. This is called a “buffer overflow” when you write to memory locations that are legal (from an operating system perspective) but could potentially be overwriting memory another part of the program will also be using.

If you continue to learn about this subject you’ll begin to understand how programs can be exploited using such “buffer overflow” techniques – even to the point where you begin to write assembly language instructions directly into areas of memory that will be executed by another part of your program.

When you get to this stage you’ll have gained much wisdom. But please be ethical and do not use it to wreak havoc in the universe!

PS when I say “operating system” above I really mean “operating system in conjunction with privileged CPU access”. The CPU and MMU (memory management unit) triggers particular interrupts or callbacks into the operating system if a process attempts to use a page that has not been allocated to that process. The operating system then cleanly shuts down your application and allows the system to continue functioning. In the old days, before memory management units and privileged CPU instructions, you could practically write anywhere in memory at any time – and then your system would be totally at the mercy of the consequences of that memory write!

Leave a Comment