Arrays don't know their own length?

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Arrays don't know their own length?

virote328
Is it true that the JACK array's don't know their own length?

suppose we make an array of size 1

array[0]; // legal
array[1]; // also legal?  

From What I can collect from the book, there doesn't seem to be anything stopping this from happening.
Reply | Threaded
Open this post in threaded view
|

Re: Arrays don't know their own length?

cadet1620
Administrator
virote328 wrote
Is it true that the JACK array's don't know their own length?
Correct. There is no Array.length() method.

[Edited]
Misunderstood the original post 8-(.
The questions is about array boundary checking.

You are correct that there is no boundary checking.

Given an array of length 1, "array[1]" will read an unknown value from beyond the array; it will write to memory outside the array, most likely corrupting the heap.

--Mark
Reply | Threaded
Open this post in threaded view
|

Re: Arrays don't know their own length?

virote328
ok, I know that this may be off topic, but The reason I brought this array length issue up was because of memory management.  I'm just wondering how in the world the Memory class knows how to deAlloc the array.  The information on length seems to be Not in the array.  In that case the memory must keep track of it some how. (in fact all, object don't seems to keep track of how many variables it has)

As I step through the VM emulator, I don't see where the Memory class is holding the info.  The book mentions an array of some sort that holds information of where an object is and how much space it is taking up.  It would be help full if someone could point me to the right line.
Reply | Threaded
Open this post in threaded view
|

Re: Arrays don't know their own length?

cadet1620
Administrator
I haven't looked at the supplied Memory.vm in too much detail, but I can tell you a bit about typical memory managers.

The allocated memory block has a fixed size header that is immediately in front of the returned memory block. As long as the program doesn't use a negative index into the returned memory block, the header will still be valid when the block is freed.

In my Memory.jack, this hidden block header contains the block size, and a linked-list pointer so that the freed blocks can be kept on a free list.

So although Memory knows how big the block is, Array doesn't.

Note that the size of the allocated block may be bigger than the requested length, so a Memory.size()  function, if it existed, would not be a substitute for Array.size()

--Mark