oliver davidson
oliver davidson

Reputation: 49

Get contents of a fixed memory location

I'm trying to access a certain location in memory and retrieve the contents of that memory location but the program seems to not work when I run it. I don't get any errors it's just a blank console screen. The first thing that came to my mind is that it would probably be a security breach to be able to access a memory location like this. Is that the reason or is my code wrong?

int main()
{
    int * pointer = 100;

    printf("%d", *pointer);

    return 0;
}

Upvotes: 0

Views: 127

Answers (1)

Andrew
Andrew

Reputation: 2312

Memory mapped registers are an integral part of embedded programming - but you need to know where in memory to prod - random locations are likely to generate random effects (due to undefined behaviour)!

For embedded compilers, usually there is a header file full of lines similar to:

#define GPIO_PORTF_DIR_R (*( ( volatile unsigned int * )0x40025400 ) )

These (a) map registers appropriately and (b) hide the specific implementation.

Note the use of the volatile qualifier - any memory mapped access should be volatile qualified, otherwise there is scope for compiler optimisation to have an effect too!

Now we can use this name inside your code to read and write to that register (wherever it happens to be):

GPIO_PORTF_DIR_R = 0xF0;
data = GPIO_PORTF_DIR_R;

The fact that your code results in "just a blank console screen" means it's not doing what you expect... your random location is causing random (undefined) behaviour.

Upvotes: 1

Related Questions