In C, I have declared a memory area like this:
int cells = 512;
int* memory = (int*) malloc ((sizeof (int)) * cells);
And I place myself more or less in the middle
int* current_cell = memory + ((cells / 2) * sizeof (int));
My question is, while I increment *current_cell, how do I know if I reached the end of the allocated memory area?
if (current_cell >= memory + cells)
no_longer_in_valid_memory;
However! You have a large problem in your code. If you want current_cell to be somewhere near the middle of the memory region, you should actually do this:
int* current_cell = memory + (cells / 2);
The pointer arithmetic will take care of the multiplying by sizeof(int).
While you're within the valid indices the following holds true:
memory <= current_cell && current_cell < memory + cells
so if you only increment the address it's enough to check for
current_cell < memory + cells
however be careful - you might increment the address by such a bug value that it overflows and becomes less than memory. Only use the second simpilfied condition if you're sure overflow can't happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With