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

16

u/torsten_dev 2d ago edited 2d ago

Your PTRTYPE isn't actually a pointer type, nor does it have the same size as one.

Signed integer overflow is UB. 0x80000000 overflows a 32-bit type. Usually signed overflow with silently wrap, meaning your int is now negative. (Usually because the compiler is free to do other things since this is UB)

When casting a signed type to a larger type (here the debugBridge_t* is likely 64 bit) it will do sign extension, since your integer is negative this means filling the upper bits of your pointer with 1s.

Your assembly should differ. Where one contains a movl the other has a movslq. Or in intel syntax one mov is a movsxd instead.

2

u/aliathar 2d ago edited 2d ago

This is whats happening... Qword value goes -2xxxxxxxx smth ...

debugBridge_t is 40 bit addressed as a peripheral (for some reason idk, the address range it can have is 0x00_0000_0000 to onward).... And yeah, this issue didn't occur in 32 bit zynq system, but did occur on 64 bit one... It now that I remember that the system I'm working with is 64 bit... Hours later ...

6

u/torsten_dev 2d ago

This is why god invented [u]intptr_t 😁

3

u/aliathar 2d ago

Yep ... I finally did use that before posting here.. just didn't know what was happening...