RajSanpui
RajSanpui

Reputation: 12064

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

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

56737856 (some output)

Now, if i am not incorrect the output that we see above is not a physical address but from the virtual address space. Am i correct?

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

Upvotes: 8

Views: 2824

Answers (3)

Nobilis
Nobilis

Reputation: 7448

Is there any way to see the actual physical address?

On an x86 architecture in real mode, there's no memory protection and you get back the actual physical address, so you can do things like overwriting the 0x0 address.

Here's a code snippet from 'Memory Management: Algorithms and Implementations in C/C++' that can crash a DOS running computer:

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

If I may quote Wikipedia:

Real mode provides no support for memory protection, multitasking, or code privilege levels. Before the release of the 80286, which introduced Protected mode, real mode was the only available mode for x86 CPUs. In the interests of backwards compatibility, all x86 CPUs start in real mode when reset.

Upvotes: 2

AnT stands with Russia
AnT stands with Russia

Reputation: 320531

Yes, on a platform with virtual memory it is an address in process address space, i.e. it is an address in virtual memory. In such systems, at the typical application level the actual physical address in RAM makes no meaningful sense whatsoever - even if it is already known at that moment, it can change at any moment anyway. The physical RAM address is beyond your control. So, at the typical application level when people speak about "physical addresses", they normally refer to what you printed - the address in the process address space, i.e. the virtual address.

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

Upvotes: 3

user149341
user149341

Reputation:

All addresses you see in user space applications are virtual addresses.

Physical addresses are only of concern to the kernel. The mapping from virtual to physical addresses is complex, given that:

  • Not all virtual addresses have physical addresses at all. (For instance, pages that are unmapped, lazily zero-filled, or swapped out have no physical address.)
  • Physical addresses may change without warning (e.g, if a page is swapped out and back in, or if a shared page is copied).

Outside of some very unusual situations (mostly having to do with messing around with hardware), you should not care about physical addresses.

Upvotes: 11

Related Questions