Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting an integer constant to a pointer

Tags:

c

pointers

I don't understand what this line does:

((struct Example*) 0x10000)

I've written a test program:

#include <stdio.h>

struct Elf{
    int bla;
    char bla2;
};

int main(){
    struct Elf *elfPtr;
    printf("Before casting: %p\n", elfPtr);
 
    elfPtr = ((struct Elf *)0x10000);
    printf("After casting: %p\n", elfPtr);
 
    return 0;
}

The output is:

Before casting: 0xb776dff4

After casting: 0x10000

Does this line only do this?

elfPtr = 0x10000

2 Answers

This does set the pointer to a specific constant value, which is a bad idea in systems with virtual memory management.

One notable exception is embedded systems with memory-mapped resources. In systems like that, hardware designers often reserve a range of memory addresses for alternative use, giving the programmer access to hardware registers as if they were part of the regular memory space.

Here is an example *:

struct UART {
    char data;
    char status;
};
const UART *uart1 = 0xC0000;
const UART *uart2 = 0xC0020;

With this setup in place, an embedded program can access UART's registers as if they were struct's members:

while (uart1->status & 0x02) {
    uart1->data = 0x00;
}


* UART stands for Universal Asynchronous Receiver/Transmitter, a piece of hardware commonly used for asynchronous peer-to-peer communication.
like image 131
Sergey Kalinichenko Avatar answered Dec 30 '25 23:12

Sergey Kalinichenko


Normally, assigning an arbitrary value to a pointer is a bad idea. That's why the compiler discourages it, and you need to add the cast to reassure the compiler that you know what you're doing.

(Your code is going to treat the memory at address 0x10000 as a struct Elf instance, and at least in your simple example, it's not. It might not even be readable and/or writable memory, so you'll get a crash when you try to access it.)

like image 44
RichieHindle Avatar answered Dec 30 '25 22:12

RichieHindle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!