Meditation, The Art of Exploitation

Thinking? At last I have discovered it--thought; this alone is inseparable from me. I am, I exist--that is certain. But for how long? For as long as I am thinking. For it could be, that were I totally to cease from thinking, I should totally cease to exist....I am, then, in the strict sense only a thing that thinks.

Tuesday, May 16, 2006

Memory as a programming concept in C and C++, multi-dimensional arrays

C and C++ catogerize multi-dimensional arrays into two distinctively different kinds, static and dynamic.

Static multi-dimensional arrays are declared and defined at compile time. They are internally represented as one dimensional array and accessed through index arithmatic (addition and multiplication). For example, x[i][j] (whose size is nrow * ncol) is accessed by *(x + i*ncol + j) . Because they are represented in such a manner, they must be passed to functions with explicit array bounds information (except that the first dimension bound nrow can be omitted, x[3][4] can be passed as x[3][4] or x[][4]). Due to the same reason, static multi-dimensional arrays are passed by reference, namely the pointer value that points to the storage. C and C++ don't pass multi-dimensional arrays as values as that would require a tremendous amount of overhead involving momory copy, passing additional array structure information onto the stack call frame, even though the function declaration with static multi-dimensional array resembles pass-by-value semantics. The next example demonstrates the sutleties of C and C++ static multi-dimensional arrays:

#include

int a[3][4] = {0, 3, 4, 2, 1, 5, 6, 9, 8, 3, 2, 5};

void adjust(int x[][4]){

x[0][3] = 80;

}

int main(){

printf("a[0][3] = %d\n", a[0][3]);
adjust(a);
printf("a[0][3] = %d\n", a[0][3]);

return 0;
}

Dynamic multi-dimensional arrays are declared using pointer sematic and defined at run time, thus 'dynamic'. They are internally repesented as dynamic 1D arrays whose elements are pointers that point to sub-level dynamic 1D arrays. They are accessed by dereferencing pointer values. For example, int ** x is a pointer to 2 dimensional dynamic array; at run time, it's defined to point to an array of shape x[3][4],

x = malloc(3*sizeof(int *));
for(int i = 0; i < 3; i ++)
x[i] = malloc(4*sizeof(int));

It's important to distinguish between static and dynamic multi-dimensional arrays in C and C++ because even they are both multi-dimensional arrays, their definition, representation and access methods are so vastly different, they can be confusing even among the most seasoned developers.