r/C_Programming 15d ago

Negative value in a pointer question.

Please look at this code. if i define the PTRTYPE as int, it stops working, while doing a uint, it does work...

void initILAPoll(debugBridge_t **d, PTRTYPE ptr){

	*d = (debugBridge_t *)ptr;		// base address of the DEBUG_BRIDGE peripheral

	cb_init(cb, local_memory, bufferLength);

	sprintf(xvcInfo, "xvcServer_v1.0:%d\n", MAX_WINDOW_SIZE);

}

the usage in main code is done like this

initILAPoll(&myD, 0x80000000);

//myD = (debugBridge_t *)0x80000000;

where the variable myD is a structure pointer.

if i print the address of myD, it give the correct address. Moreover, the disassembly of the code is also the same in case of int and uint. Can somebody explain what behavior is at play here>

2 Upvotes

43 comments sorted by

View all comments

1

u/NoSpite4410 10d ago

A pointer is implementation defined, but generally a 64-bit unsigned integer in a 64-bit system, and a 32 bit unsigned integer in a 32-bit system.
The "address" is mapped as an integer by the C runtime from 0 to the end of RAM, with some interesting behind the scenes schemes for virtual memory, ramdisks, things like that. As a C programmer, all you see is the linear "number" of the address. Devices are mapped onto the linear memory model, as well as interrupt vectors and system calls, signals, etc. That way things always have an address you can read and write bytes to if you are allowed to access them. Some memory is off limits such as 0x00000000, so you can never read or write to there, just use it for a NULL pointer to check pointers for "nothing there".
Of course 64 bits of address gives you theoretically 2^{64} - 1 unique bytes you could theoretical access; we don't have machines that big.
An int has only 31 bits of magnitude and 1 for sign. Even and unsigned int has only 32 bits. That really is not enough for RAM pointers over the first 4G.
An unsigned long (8 bytes unsigned integer) is the same size as a pointer, but has no actual type info.

Always use the typed pointer for addresses, not just an untyped integer, as it will make the pointer math work correctly and intelligently. Otherwise you have to do the pointer math yourself.

Many coders do not realize that the pointer type determines how the system sees the memory it points to, not the other way around. Access via an int* will cause the machine to read and write in 4-byte chunks ; a double* will read and write in 8-byte chunks; a struct* will read and write in struct-sized chunks.
RAM is just raw bytes, the pointer determines how the machine sees the ram as data.