PC RAM and process address space

Suppose I have 3 gb of ram and 250 gb hard disk in my pc.
Now I wrote a simple C program having only one statement malloc() to allocate 4 gb of memory as 32 bit os can address 4gb address space then will the malloc succeed?
If yes then how it will get extra 1 gb of memory?
Does the process gets memory only from RAM or also from harddisk?

malloc cannot succesfully make a request for memory that exceeds virutal memory. virtual memory = RAM + swap.

So the answer is no.

You also have to factor in the memory used by resident programs, and memory used by the OS itself.

1 Like

A malloc() for 4 gigs of RAM on 32-bit probably would not succeed. There's a limit of 4 gigabytes per process in 32-bit and the process must have some memory already, for stack space, C libraries, and so forth. It'd never find room for an entire 4 gigabytes left over.

How about allocating 2 gigs of RAM on a 32-bit system with 1 gig of memory? That's a lot more possible.

The answer, actually, depends on your operating system.

On a Linux system, it wouldn't allocate any memory or swap space at all. It'd just mark down that the process has 2 gigs of RAM at this address range. No pages would be allocated until the process used it.

On most other UNIX systems, you need to use exactly as much swap as memory that's being allocated, with no exceptions. To allocate 2 gigs of RAM you need 2 free gigs of swap, period. It's possible to have more swap than RAM, so you can allocate more memory than your system has and the system will use swap to make up the difference.

1 Like

Did you even try to compile it...because if you gave the right switches for a 32-bit compilation it will give a runtime error and if it didnt that's because the default compilation on linux is 64-bit meaning the malloc will succeed.

1 Like