0

This c code returns the value at a memory address.

value = MemoryRead((ptr))

MemoryRead is a #define defined as

#define MemoryRead(A) (*(volatile unsigned char*)(A))

How does this work? Could somebody explain how this returns a value at an address?

Ivan Rubinson
  • 3,001
  • 4
  • 19
  • 48
  • 2
    This has been asked and explain hundreds of times before. Please do some research on SO before asking a question. – Lundin Jun 28 '16 at 08:48

1 Answers1

3

*(addr) returns the value stored at addr.

The above code looks self explanatory. If you dry run.

Consider value = MemoryRead((ptr))

Becomes value = (*(volatile unsigned char*)((ptr)))

The #define looks really cryptic at first. The way to understand this is by breaking it down into pieces, as done here;

First of all,

unsigned char

means we are using a byte-sized memory location. Byte being 8-bits wide.

unsigned char *

means we are declaring a pointer that points to a byte-sized location.

(unsigned char *) (ptr)

means the byte-sized pointer points to address ptr. The C compiler will refer to address ptr. The assembly code will end up using ptr in Load(LD) and Store (STR) instructions.

(*(unsigned char *)(ptr))

The first asterisk from the left signifies that we want to manipulate the value in address ptr. * means “the value pointed to by the pointer”.

volatile

volatile forces the compiler to issue a Load or Store anytime MemoryRead is accessed as the value may change without the compiler knowing it.

So any address entered at ptr will be directly accessed by your code. (If the address is present in memory.)

Matt
  • 74,352
  • 26
  • 153
  • 180
Sunny R Gupta
  • 5,026
  • 1
  • 31
  • 40