Week 3: Pointers Flashcards
When a variable is declared, what determines how much memory is assigned to the variable?
The type of the variable determines the amount of memory assigned to it. For example, an integer is 4 bytes, thus would be allocated 4 contiguous memory cells. [ 2^(4*8) ]
What type is a pointer?
A pointer is its own data type that is unique to the type it points to. For example, a pointer to an integer is a type pointer that points to an integer.
Give an example of how you would use a triple pointer? (Code an example if possible)
p points to x, q points to p, z points to q. Triple dereference q would give the value of x.
What does the variable of an array point to?
The memory address of the first element of the array.
What does a pointer to an array point to?
The memory address of the first element of an array.
If pointing to the beginning of an int array, in regards to output, what happens if the pointer is incremented by 4?
The pointer moves 4 indexes up the array, meaning each pointer incrementation moves 4 bytes along the array. In general, when a pointer is incremented, it will increment that same number of bytes of the data type it’s pointing to.
When does malloc assign the memory?
At run time.
Why are void pointers useful in memory allocation?
When we are not sure which data type we will be mallocing, thus using a void pointer means we can cast at a later time.
What are the 3 methods of dynamically allocating memory? What are the issues with 2 of them? Why is the 3rd method best practice?
- Declare an array whose size is decided at run time -> We don’t know how much free memory is available, or how much we need.
- Process the data into smaller chunks -> Very complex.
3 Use pointers (Malloc) -> Can check whether memory allocation was successful.
Describe how malloc works…
Malloc asks the OS for X amount of contiguous bytes in memory from the heap. X depends on the data type of the malloc. The OS will assign the memory providing there is contiguous memory available.
When calling malloc, what happens if the requested memory available is fragmented?
Malloc will not assign the memory. Malloc will only ever return contiguous memory.
What does malloc return?
A void pointer to the first address of the assigned contiguous memory.
Why should we cast what malloc returns?
To cast the returned void pointer to the correct data type.
How do we know if malloc has failed?
It returns nil.
What are the 2 runtime errors that pointers can cause? What causes them?
Memory fault and segmentation fault.
1 - Caused by pointers trying to access memory it’s doesn’t have rights to.
2- Caused by pointers trying to access memory in an illegal way i.e overwrite OS files.