SE250:March 7
Announcement
Agenda
- Minute taker: stsa027
- C revision: pointers, arrays, structures
Minutes
In preparation for the Lab on March 11, time was spent to cover concepts related to pointers and addresses such as how memory is organised in C and how this compares to the actual hardware in the computer.
Each byte of memory is given a different memory address and is numbered in a consecutive way. In 32-bit systems, all memory addresses are 4-byte values. This causes a problem where the maximum number of memory addresses available cannot exceed 2^32, which means that maximum memory is also limited at 2^32 bytes, or 4GB. This increases to 2^64 bytes (or 8GB) in 64-bit systems, where memory addresses are 64 bits.
edit: [1] has got memory limit for a 64bit system at 17.2 billion gb. 2^64 bits is not twice as big as 2^32, but 2^32 times bigger.
Since all addresses are 4-bytes, all pointers (variable that stores the memory address or reference of another variable) are also 4 bytes in size. However, the variable being pointed to can vary in size depending on the variable type. E.g. int variables are 4 bytes while double variables are 8 bytes in size.
To display the memory address of a declared variable (whether or not it has been initialised), we can use:
printf("%p", &x);
The ampersand sign can be translated as 'address of' and in this case, 'address of x'. The address is displayed in Hexadecimal form.
The 'reverse' of the ampersand sign is the asterisk. It can be used to assess the data with the memory address referred to by a pointer. For example:
int x = 100; int *ptr; //declare pointer 'ptr' ptr = &x; //let the memory address of x become the value of ptr printf("%d", *ptr); //this will display 100
C maintains a limited illusion that memory is made up of different sized chunks instead of in bytes. We see can this in int variables, which are 4 bytes, and doubles which are 8-bytes. This illusion is sustained also by the malloc function.
The malloc function allocates memory for a program to use, but is uninitialised. The malloc function allows variables to outlive a function. malloc has an advantage over creating global variables because memory used by malloc can be freed by using the free function. However, the nature of malloc gives it several disadvantages:
- Firstly, malloc itself uses a sizable chunk of memory (in the MB range).
- Secondly, because malloc allocates memory to variables in a non-ordered fashion, it must keep track which bytes of memory is being used, and by what. This required additional memory, and if used for small peices of data, is especially inefficient. (The example given was using malloc for a 4-byte piece of data, where malloc used an additional 12 bytes.)
- Thirdly, because malloc tends to cause memory leaks if the 'free' function is not called.
Taken by stsa027 7 March 2008.