tags:

views:

92

answers:

4

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?

+3  A: 

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.

sharptooth
are you sure it's not cells*sizeof int? that was my doubt.
klez
@klez: Certainly no `*sizeof()`. With a `type*` pointer `(type + N)` points onto the Nth element - the compiler will do the `*sizeof(Type)` multiplication.
sharptooth
It is not. When you use + or - with a pointer and an integral type, it adds or subtracts *elements*, not bytes.
Mike DeSimone
+6  A: 
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).

sharth
+1  A: 

And I place myself more or less in the middle

int* current_cell = memory + ((cells / 2) * sizeof (int));

Actually, no. The correct expression would be:

int* middle = memory + cells / 2;

since pointer arithmetic takes the type of the pointer into account. In other words, this expression:

memory + 1

increments the pointer not by a single byte but by sizeof(int) bytes.

Konrad Rudolph
+1  A: 

The index in the array, which starts at memory, equivalent to the pointer current, is just current - memory -- the "scaling" (by sizeof(int)) is taken care of for you. So, you know the pointer is valid (i.e., within the bounds of the cells-long array starting at memory) if and only if the index is >=0 and <cells (from 0 to 511 included, in your example):

((current - memory) >= 0) && ((current - memory) < cells)
Alex Martelli