Click here to Skip to main content
15,851,242 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Say I've allocated some memory using malloc(), the operating system will give me the address to the memory allocated (i.e. a page). Now I am trying to browse this area of memory as if it was a 16-bit address space which starts from 0 and ends at 0xFFFF. (Don't ask why!, Just wanted to understand some concepts)
So I wrote this routine which will convert the so-called "virtual" address into a physical one:
uint32_t* virtual_to_physical(uint16_t OFFSET, uint32_t* MEMORY_BUFFER)
	uint32_t* a = MEMORY_BUFFER + OFFSET;
	return a;

Basically this routine will get the malloc()ed buffer and then will add the offset and return the physical address.
Now when I try it like this:
uint32_t* physaddr = (uint32_t*)malloc(0xFFFF);
printf("\nmalloc()ed buffer: %p", physaddr);
uint32_t* new_addr = virtual_to_physical(1, physaddr); //! Get the physical address of offset 1 in the malloc()ed buffer
printf("\nVirtual Address 1 turned to physical address: %p", (uint32_t*)new_addr);

But the output I get is:
malloc()ed buffer: 0x12b90a0
Virtual Address 1 turned to physical address: 0x12b90a4

Instead of adding 1 to the Physical address it increments it by 4?
Updated 23-May-14 22:57pm

1 solution

Yes. It does - that is what I would expect.
Think about it: What datatype is your memory buffer? It's a uint32_t (because MEMORY_BUFFER is declares as a pointer to uint32_t) which means it addresses 32 bit quantities, so when you add 1 to the pointer it moves it to the next uint32_t values, not the next byte in the memory. Physical addresses are always in bytes - or you wouldn't save any memory space when you used characters r byte values - but pointers always point to a "whole" value of the type of the pointer - or moving up through an array of integers would be a PITA! :laugh:

If you want to work in byte increments, then use a pointer to an unsigned char, or other 8 bit datatype in your system.
Share this answer
sid2x 24-May-14 4:50am    
Silly me!, Thanks for the quality answer, I now use uint8_t and the code works as expected.
[no name] 24-May-14 4:57am    
A perfect answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900