tags:

views:

121

answers:

3

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?

+14  A: 

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

Mehrdad Afshari
+3  A: 

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.

paxdiablo
I fail to see how you could perform any reasonable arithmetic on sequential ids to access different bytes within the allocated blocks.. ;-) Perhaps sequential ids in the upper 32 bits and an offset in the lower 32 bits?
R..
I didn't say it would be reasonable, just possible :-) Provided the code generated for indexing (`x[]` and `*(x+n)`) and comparisons (and possibly other things) was convoluted enough to handle the sequential nature, it could be made workable. I certainly wouldn't want to develop or use such a system but that doesn't make it any less possible according to the standards. For example, the shifting of the memory ID up by 32 bits (as you propose) could be automated in the generated code. My point is you should only make assumptions that are specified by the standard.
paxdiablo
A: 

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.

Jander