1
votes

In a K&R ebook I've been reading I came across this code:

code

And my concern was in the line:

allocbuf + ALLOCSIZE - allocp >= n

The code takes the address of where the buffer begins and calculates, using the index of the pointer to itself as well as the maximum buffer length constant defined above, the total remaining allocations.

Now, I understand that if you were to define a character pointer, for example, then were to arithmetically increment it by one:

char *ptr = "array";
ptr++;

Then you would get the second position, 'r' above, in memory. The, in memory, actually increments by sizeof(char) units.


So, given that arrays operate under the guise of pointers:

allocbuf + 10000 

Is the final allocated slot in the array, correct? Since the pointer is of type char, 10000 'slots' later is actually 10,000*sizeof(char) slots later.

To clarify this concept in my mind, given a random memory address say 4210720, does 4210721 represent a bit, byte or some other metic past the address?

That is:

void *ptr = "sherrellbc";
ptr++;

Where is ptr now? Is it at some pointer between the 's' and 'h' since type void gives no information regarding step length (as in, a char pointer would increment by sizeof(char)).

In essence, what metric is memory stored using? Bits bytes, nibbles, etc?

3
Wait a minute: void *ptr = "..."; does not compile in the first place. ptr++ increases the memory address, whatever it is represented in, by sizeof(*ptr). - Djee
void *ptr = ".."; does compile for me. Incrementing the ptr also does not result in an error insofar as compiling is concerned. I have not done any experiments as to what is happening, however. I am not that concerned with it. - sherrellbc

3 Answers

2
votes

Memory addresses are byte addresses on every computer you're likely to use, even ones that don't have byte-level memory operations. Some compilers define incrementing a void * as adding one to the pointer, but it's not portable.

1
votes

Dereferencing an void pointer is undefined in nature. In case the type is defined the increment will always

ptr+1 = next address of ptr type.
1
votes

allocbuf + 10000 Is the final allocated slot in the array, correct?

It's one past the end.

To clarify this concept in my mind, given a random memory address say 4210720, does 4210721 represent a bit, byte or some other metic past the address?

A byte (3.6):

"addressable unit of data storage large enough to hold any member of the basic character set of the execution environment.

NOTE 1 It is possible to express the address of each individual byte of an object uniquely."

Finally,

void *ptr = "sherrellbc"; \n ptr++; - Where is ptr now?

Arithmetic on void* is illegal. Don't use it ;) It's like asking the compiler to take the address held by the variable and adding sizeof(void) to it.

If it must come down to this, use char* instead.