Simulation of following code, compiled with V6.12 and optimzation level -O2
#include <stdio.h> typedef struct { char data[23]; } device_t; static device_t deviceList[100]; static device_t* rotate(device_t *device) { int index; index = (device - &deviceList[0]) + 1; if (index < 0 || index > 30) { index = 0; } printf("index = %d\n", index); return &deviceList[index]; } int main(void) { unsigned int n = 0; while (1) { printf("n = %d: ", n); rotate((device_t*)(n)); n += 1000; } }
prints n = 0: index = 0 n = 1000: index = 0 n = 2000: index = 0 n = 3000: index = 0 n = 4000: index = 0 n = 5000: index = 0 n = 6000: index = 163395741 n = 7000: index = 350133493 n = 8000: index = 536871245 n = 9000: index = 723608997 n = 10000: index = 910346749 n = 11000: index = 1097084501 n = 12000: index = 1283822253 n = 13000: index = 1470560005 n = 14000: index = 1657297757 n = 15000: index = 1844035509 into Debug (printf) Viewer, which is obviously incorrect. Maybe a bug, or do I missunderstand something?
you are rigth, I am violating the C Standard, 6.5.6 ISO/IEC 9899:2011
Thank you very much
For clarification.
The function
device_t *rotate(device_t *device);
returns next element to device. If device is last element, the first element is returned. If device does not point to an valid object in list, any list element could be returned.
If device does not point to an valid object in list, any list element could be returned.
Except that that part of the intended function is just impossible to implement without causing undefined behaviour via C99 6.5.6 or 6.5.8 along the way. In other words: forget about it.
If that's what you have to achieve, you have to change the signature from handling pointers to handling indices into the array.
In short: in C, there's no such thing as deriving a trustworthy pointer from garbage input. The only checks you can do on untrustworthy pointers are trivial variations on
(ptr != 0) (ptr == 0)
Thanks for your advice.