简体   繁体   中英

Is the return value of malloc a virtual or physical address?

Is the address returned by malloc a virtual address or is it the actual physical address where the memory is allocated?

Edit:

I read somewhere "In some implementations, calling free() releases the memory back to the system and in others it is released back to the process". Does "releasing back to the system" imply that the memory is the actual physical memory and "releasing back to the process" mean it is virtual memory?

It's an address valid in the current process. Whether it's virtual address or physical address depends on the underlying platform.

There is no concept of real or virtual memory in the C standard so the question is meaningless. An implementation is free to do it however it wishes.

In a virtual-memory OS, you will almost certainly get a virtual address. In a non-virtual-memory OS, you probably won't.

What you will get in both cases is an address you can use for all the usual things C provides addresses for, such as de-referencing, freeing, reallocating and so forth. That is your only guarantee, and also the only thing you usually need to concern yourself with.

It's free to give you a list of sequential IDs (1, 2, 3, ...) if it wishes, provided all the expected operations still work as advertised. Granted that may not be very efficient in the current architectures but it's still workable.

The only reason I can think of that you would care about a physical memory address is if you're trying to talk directly to some piece of memory-mapped hardware... in which case you need something much more down-to-the-metal than malloc() . You'd have to use a kernel or driver interface, or barring that, go behind the operating system's back using something like UNIX's /dev/mem -- or, better, write a driver yourself to map the needed physical memory into your application's virtual memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM