Pointer bounds checking

Posted By: Saturnus

Pointer bounds checking - 07/30/09 08:46

Hello,

I have an array allocated at runtime and I would like to check, if a pointer points to a location in memory that belongs to that array.

Does somebody know how/if I can do that in lite-C?

Thanks
Posted By: Quad

Re: Pointer bounds checking - 07/30/09 09:30

yes you can skim thru the array in loop and chck all elements one by one, check if they're same with your pointer
Posted By: Saturnus

Re: Pointer bounds checking [solved] - 07/30/09 11:02

Thank you, Quadraxas.
Yes, this was possible. However, I was wondering if there was a more efficient way to do this.

And indeed there is by just comparing the pointers. It's an obvious thing actually. : )

Code:
int *arr = malloc(sizeof(int) * 100);
int *ptr = &arr[50];

if ((ptr >= &arr[0]) && (ptr <= &arr[99]))
	printf("within bounds");
else
	printf("out of bounds");


© 2024 lite-C Forums