CS402: Worksheet 2 Memory Management 1 Allocating Memory

advertisement
CS402: Worksheet 2
Memory Management
1
Allocating Memory
If the size of an array is known at compile time, then it can be declared using similar syntax to
Java:
// Create an array of ints and initialise it .
int my_array [] = {10 , 11 , 12 , 14 , 15};
printf ( " The first element is % d \ n " , my_array [0]) ;
// Create an array with space for 10 ints .
int x [10];
If the size of the array isn’t known at compile time (e.g. it depends on a command line argument,
or user input) then it must be allocated at run time with a call to the malloc function.
An array in C is a contiguous block of memory. If an array contains 10 integers, for example,
then this is stored in memory as 10 integers one after the other. malloc returns a pointer to the
first element, and can be used as below:
int * my_malloc_array ;
// Allocate space for 10 ints .
// sizeof () returns the number of bytes required to store an int
my_malloc_array = ( int *) malloc ( sizeof ( int ) * 10) ;
Task 1
When malloc creates memory, it is not typed (it returns a void pointer) or initialised (the
memory contents are junk).
Write a function called my malloc that allocates a user-specified number of ints and initialises
them to a user-specified value (e.g. my malloc(25, 3) should return a pointer to 25 ints, all set
to 3).
1
2
Pointers to Pointers to Pointers...
Pointers can contain any arbitrary memory address (32-bit or 64-bit depending on the machine).
In other words, they can point to any location in memory – even that of another pointer.
The following example demonstrates one way that this feature can be used to create a two
dimensional array:
// Create an array with space for 10 int pointers .
int * x [10];
// Allocate space for 100 integers as a 2 D array .
int i ;
for ( i = 0; i < 10; i ++) {
x [ i ] = ( int *) malloc (10* sizeof ( int ) ) ;
}
printf ( " Value at x [0][0] = % d \ n " , x [0][0]) ;
Task 2
One problem with the above code snippet is that the 10 arrays are not necessarily contiguous in
memory. You can check this by printing the memory addresses of x[0][9] and x[1][0].
Write a program that instead allocates one large chunk of memory (e.g. 100 integers) and uses
pointers to treat the memory as a 2D array.
2
Download