Is the memory address returned by malloc / calloc from the virtual address space?

char *ptr = (char*) malloc(40); printf("%u",ptr); 56737856 (some output) 

Now, if I'm not mistaken, the output that we see above is not a physical address, but from a virtual address space. Am I right?

Is there any way to see the actual physical address? Or vice versa (if my assumption is wrong), and the entire internal implementation of malloc necessarily uses the jemalloc algorithm?

+7
source share
3 answers

All addresses that you see in user spaces are virtual addresses.

Physical addresses refer to the kernel only. Mapping from virtual to physical addresses is complex given that:

  • Not all virtual addresses have physical addresses at all. (For example, pages that don’t appear, are lazily filled, or replaced, do not have a physical address.)
  • Physical addresses may change without warning (for example, if a page is unloaded and a shared page is returned or copied).

Outside of some very unusual situations (mostly hardware related) you don't need physical addresses.

+11
source

Yes, on a platform with virtual memory, this is the address in the address space of the process, i.e. This is the address in virtual memory. In such systems, at a typical application level, the actual physical address in RAM does not make any sense, even if it is already known at that moment, it can change at any time. The physical address of RAM is out of your control. So, at a typical application level, when people talk about "physical addresses", they usually refer to what you typed - the address in the process address space, that is, the virtual address.

Just don't use %u to printf pointers. Use %p . Or at least convert the pointer to the desired type of an unsigned integer and use the format specifier for that type.

+2
source

Is there any way to see the actual physical address?

In x86 architecture in real mode, there is no memory protection, and you return the actual physical address, so you can do stupid things like rewriting the 0x0 address.

Here is a snippet of code from "Memory Management: Algorithms and Implementations in C / C ++" that could lead to a crash of a computer running DOS:

 void main() { unsigned char* ptr; int i; ptr = (unsigned char *)0x0; for(i = 0; i < 1024; i++) { ptr[i]=0x0; } return; } 

If I can quote Wikipedia:

Real mode does not support memory protection, multitasking, or code privilege level. Prior to the release of 80286, in which protected mode was introduced, real mode was the only available for x86 processors. In the interest of backward compatibility, all x86 processors start in real mode when reset.

0
source

All Articles