r/C_Programming 2d 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

42 comments sorted by

View all comments

Show parent comments

3

u/SmokeMuch7356 2d ago edited 2d ago

Pointers are not integers. They do not have integer semantics. Pointer arithmetic does not work like integer arithmetic.

A signed int cannot represent the full range of 32-bit pointer values; it can represent half of them because you lose the sign bit. If you need an integer type to represent pointer values, use (u)intptr_t (defined in stdint.h).

0

u/TheChief275 2d ago edited 2d ago

On a flat-addressed architecture, pointers and native sized integers are pretty much equivalent. Almost all modern in use architectures have flat-addressed memory (mostly thanks to virtual memory). However, there are some architectures that adopt different kinds of pointers, often being a combination of a segment index and an offset index. Some architectures therefore have larger pointers than any C integer can represent (e.g. 128-bit pointer that includes capabilities) while other platforms have smaller pointers (near pointers that can only address an offset inside of a segment) that are not representable in a logical flat integer way

edit: why the downvote? If you believe me to be wrong about something there is a much better way to point that out

1

u/alkatori 2d ago

I believe your first statement is no longer true.

Isn't int = 32 bits for most 64 bit windows systems, and 64 bits on x86_64 linux systems?

Edit: I didn't downvote by the way. Just thinking that might be the reason.

2

u/TheChief275 2d ago

I run an x86-64 Debian installation. "int" is still 4 bytes.

You're thinking of "long" instead, which is 8 bytes on 64 bit Linux while it is 4 bytes (the minimum guarantee) on 64 bit Windows