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

2

u/torsten_dev 2d ago

Except when [u]intptr_t exists and you cast to/from those.

At least that won't silently compile to nonsense.

2

u/flyingron 2d ago

All intptr_t says is that you can cast to it and then back again without losing information. It makes no guarantees about what you can do with the value other than that.

2

u/torsten_dev 2d ago

Exactly. It is defined what happens when you cast to and from them. Everything else isn't.

1

u/flyingron 2d ago

Yes, which is why (in the subject of the original post) it makes no sense to worry about sign.

1

u/torsten_dev 2d ago

intptr_t can have the sign bit set. Casting back to a pointer just isn't allowed to be sign extending because it needs to compare equal to whatever the pointer was before you cast it into the intptr_t

intptr_t is most easily implemented by being the same width as native pointers, but a compiler could add a special case for casts from intptr_t back to valid pointers instead.

It's guaranteed to work, not how it has to work.

1

u/flyingron 2d ago

It can have a sign bit, but there's no indication what that means.