
pointer to array - memory usage
On 29 Apr 2003 15:46:06 GMT,
Quote:
> Dear Reader,
> I have a question with respect to the used RAM
> during execution of the following compiled C-code
> (to ease my description I put line numbers):
> -------------------- begin code -------------------
> 1 #include <stdio.h>
Why did you include this header?
Quote:
> 2 #include <stdlib.h>
> 3 float array[10000][1000][10];
You're asking for an object with 100000000 * sizeof(float) bytes.
There is no guarantee that that is possible. On my platform that
translates roughly to 381 MB. Also see later comments.
You know that all elements of this array will already be initialised
to 0.0, right?
Quote:
> 4 float *arrayPtr;
> 5 int iCount, jCount, kCount;
> 6 int main ()
> 7 {
> 8 arrayPtr = &array[0][0][0];
> 9 for ( iCount=0 ; iCount<1000 ; iCount++ ){
> 10 for ( jCount=0 ; jCount<10000 ; jCount++ ){
You have the boundaries for iCount and jCount mixed up.
Quote:
> 11 for ( kCount=0 ; kCount<10 ; kCount++ ){
> 12 *(arrayPtr + iCount*10000 + jCount*10 + kCount) = 0.0;
Where the 10000 here is, of course (10 * 1000), not the 10000 from the
first index. It's potentially confusing when you use numbers like
this.
Quote:
> 13// *arrayPtr++ = 0.0;
Why are you using a pointer anyway? Why not simply (assuming you fix
up the boundary conditions in the loop conditionals):
array[iCount][jCount][kCount] = 0.0;
Much more readable (and maintainable) than the calculation, and more
natural than the pointer increment.
Quote:
> 14 }
> 15 }
> 16 }
> 17 return 0;
> 18 }
> -------------------- end code -------------------
> Obviously this code initializes an array by using a pointer.
> By using "line 12" where the pointer position is
> calculated each loop, the memory use of the executable file is
> low (appr. 20 MB). However, when I use "line 13" instead of
> "line 12" (change the comment signs) the memory use of the
> executable file increases drastically (appr. up to 100 MB).
I'd say that this is an implementation detail of your implementation,
or maybe it has to do with the fact that you got your loop boundaries
wrong, which means that when you position the pointer yourself, you
actually don't initialise all elements. Maybe your implementation does
something nifty with large objects like this, and doesn't actually
claim memory for it from the OS until you address elements. You should
maybe ask about that in a group that talks about your implementation.
For me (after fixing the relevant bits) there is no difference.
Martien
--
|
Martien Verbruggen | The four hor{*filter*} of the apocalypse are
Trading Post Australia | called Abort, Retry, Ignore and Fail.
|
--