0% found this document useful (0 votes)
10 views51 pages

COMP1511 25T1 Lecture10

The lecture covers pointers, memory management, and multi-file projects in programming fundamentals. It explains how to declare, initialize, and dereference pointers, as well as the differences between stack and heap memory. Additionally, it discusses the structure of multi-file projects and introduces linked lists as a new data structure.

Uploaded by

Kaushik Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views51 pages

COMP1511 25T1 Lecture10

The lecture covers pointers, memory management, and multi-file projects in programming fundamentals. It explains how to declare, initialize, and dereference pointers, as well as the differences between stack and heap memory. Additionally, it discusses the structure of multi-file projects and introduces linked lists as a new data structure.

Uploaded by

Kaushik Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

COMP1511 PROGRAMMING FUNDAMENTALS

LECTURE 10
Pointers
Memory
LAST TIME...

For those interested, I did find


churros and ate many
TODAY...

Multi-file projects
Pointers pointers pointers
Memory and dynamic memory
WHERE IS THE CODE?

Live lecture code can be found here:


HTTPS://CGI.CSE.UNSW.EDU.AU/~CS1511/25T1/CODE/WEEK_5/
POINTERS A pointer is another variable that stores a memory
address of a variable

👏🏻👏🏻👏🏻 This is very powerful, as it means you can modify


things at the source (this also has certain
implications for functions which we will look at in a
bit)
To declare a pointer, you specify what type the
pointer points to with an asterisk:
type_pointing_to *name_of_ variable;
For example, if your pointer points to an int:
int *pointer;
Memory Stack
// Declare a variable of
VISUALLY // type int. called number 0xFF4C

WHAT IS // Assign the value 13 to


// box
HAPPENING? int number = 2; 0xFF48

// Declare a pointer
// variable that points to 0xFF44
// an int and assign the
// address of number to it
int *number_ptr = &number; number = 2; 0xFF40

// So now:
number = 13
AND
number_ptr = 0xFF40
POINTERS 1) Declare a pointer with a * - this is where you will
specify what type the pointer points to. For example, a
pointer that stores the address of an int type variable:
int *number_ptr;

2) Initialise a pointer - assign the address to the variable


with &
number_ptr = &number;

3) Dereference a pointer - using a * , go to the address


that this pointer variable is assigned and find what is at
that address
*number_ptr
POINTERS 1. Declare a pointer with
a * - this is where you
2. Initialise a pointer - assign
will specify what type
the address to the variable
the pointer points to
THERE ARE with &

THREE PARTS
TO A POINTER

3. Dereference a pointer -Using a * , go to the address that


this pointer variable is assigned and find what is at that
address
CODE CODE A simple pointers example

CODE

A SIMPLE POINTERS
EXAMPLE

howdy_pointer.c
CODE CODE Let's see and use some pointers. Now remember that
you can only return one thing back to main and you
CODE can't return an array*

The problem is this:


ARRAYS AND POINTERS AND
FUNCTIONS - LET'S BRING IT Swap two numbers in a function call
ALL TOGETHER...

So without using pointers, can you have a swapping


function that swaps out two things? How would you
pointer_function.c
return both of those things back to the main?
REVISITING stack

MEMORY

heap

global/static
variable
code
REVISITING Stack memory is where relevant information about
your program goes:
MEMORY which functions are called,
what variables you created,
High Address Once your block of code finishes running {}, the
function calls and variables will be removed from
stack
the stack (it's alive!)
It means at compile time we can allocate stack
memory space (not at run time)
The stack is controlled by the program NOT BY THE
developer
REVISITING Start running the main

MEMORY stack

main()
REVISITING Allocate space for the variable number in main

MEMORY stack

main()
int
number
REVISITING Allocate space for the variable number2 in main, and assign value
5 to it
MEMORY stack

main()
int
number
int
number2 = 5
REVISITING Allocate space for the variable number3 in main, and assign value
-1 to it
MEMORY stack

main()
int
number
int
number2 = 5
int
number3 = -1
REVISITING Allocate space for the variable number_ptr in main, and assign the
address of number2 to it
MEMORY stack

main()
int
number
int
number2 = 5
int
number3 = -1
int *
number_ptr =
REVISITING Call function sum() (remember we go on the right first and then
assign to the left!) and allocate memory space on the stack
MEMORY stack

main()
int
number
int
number2 = 5
int
number3 = -1
int *
number_ptr =

sum()
REVISITING Allocate space for variable number in the sum function call and
assign the value 10 to it. THen change the value by adding 5 to it
MEMORY stack

main()
int
number
int
number2 = 5
int
number3 = -1
int *
number_ptr =

sum()
int
number = 10 15
REVISITING Deallocate the stack memory of sum() and return 15 to the main
function. Allocate space for number and assign 15 to it.
MEMORY stack

main()
int
number
int
number2 = 5
int
number3 = -1
int *
number_ptr =
int
number4 = 15
REVISITING Deallocate the stack memory for main and return 0 to finish

MEMORY stack
So far we have talked a bit about how variables are stored
QUICK in memory, and live in their world {} in the stack memory
REHASH This means that if we create data inside a function, it
will die when that function finishes running
This is memory that is allocated by the compiler at
MEMORY compile time...
// Make an array
int *create_array(void) {
int numbers[10] = {0};
// Return pointer to the array
return numbers;
}
//However, when we close the curly brakes,our
//array is killed, so we are returning a
//pointer to memory that we no longer have...
REVISITING A helper function cannot return a pointer of a stack variable! So
how can be deal with this? You can return by copying it or putting
MEMORY it into a more permanent storage - yay the heap!

heap Unlike stack memory, heap memory is allocated by the


programmer and won't be deallocated until it is explicitly freed by
the programmer also! You have a great power now... but with
great power comes great responsibility!
We do have the wonderful opportunity to allocate
BUT WHAT some memory by calling the function malloc() and
HAPPENS IF letting this function know how many bytes of memory
we want
I WANT TO this is the stuff that goes on the heap!

SAVE SOME this function returns a pointer to the piece of


memory we created based on the number of bytes
MEMORY? we specified as the input to this function
this also allows us to dynamically create memory
as we need it - neat!
MALLOC()
This means that we are now in control of this
memory (cue the evil laugh!)
It would be very impolite to keep requesting memory to be
WHAT IF I made (and hog all that memory!), without giving some
RUN WILD back...
This piece of memory is ours to control and it is
AND JUST important to remember to kill it or you will eat up all

KEEP the memory you computer has... slow down the


machine, and often result in crashing... often called a
ASKING memory leak...
A memory leak occurs when you have dynamically
FOR allocated memory (with malloc()) that you do not
MEMORY? free - as a result, memory is lost and can never be
free causing a memory leak
You can free memory that you have created by using
FREE() the function free()
We can use the function sizeof() to give us the
HOW DO I exact number of bytes we need to malloc (memory
KNOW HOW allocate)

MUCH
MEMORY TO
ASK FOR
WHEN I USE
MALLOC()

SIZEOF()
Using the malloc() function:
FORMAT
if you need to have space for
more than one element, you
MALLOC() multiply it by the number of
elements you need

the pointer that using the


malloc will return function
to indicate the
specify data
start of the
type that
portion of space it
you need
has allocated
Using the malloc() function example
FORMAT

MALLOC()
heap This will create a piece
of memory of 10 * 4
bytes = 40 bytes and
ptr = 0x0000 (40 bytes)
return the address of
where this memory is
in ptr
Using all of these together in a simple example:
PUTTING IT
ALL
TOGETHER:

MALLOC(SIZEOF())
FREE()
WHAT ARE Let’s see how arrays decay to a pointer...

ARRAYS?
DECAY TO POINTERS...

array_decay.c
BREAK TIME...

Jax and Juno have fallen in love (via the internet) and Jax
wishes to mail her a ring. Unfortunately, they live in the
country of Kleptopia where anything sent through the mail
will be stolen unless it is enclosed in a padlocked box. Jax
and Juno each have plenty of padlocks, but none to which
the other has a key. How can Jax get the ring safely into
Juno’s hands?
Remember that when we access members of a struct
STRUCTS we use a .
AND
POINTERS

-> VERSUS .
What happens if we make a pointer of type struct?
STRUCTS How do we access it then?
AND
POINTERS

-> VERSUS .
Those brackets can get quite confusing, so there is a
STRUCTS shorthand way to do this with an ->
AND There is no need to use (*jax_ptr) and instead can just
straight jax_ptr ->
POINTERS

-> VERSUS .
Now that you have become comfortable with arrays,
WHY ARE we are going to become acquainted with another
YOU important data structure (drum roll please 🥁):
HURTING US
WITH ALL The one and only LINKED LIST 🥳
THIS STUFF?

WE HAVE COME TO
THE ULTIMATE
REVEAL.
MULTI-FILE Big programs are often spread out over multiple
files. There are a number of benefits to this:
PROJECTS Improves readability (reduces length of
program)
WHAT ARE You can separate code by subject (modularity)
Modules can be written and tested separately
THEY? So far we have already been using the multi-file
capability. Every time we #include, we are actually
borrowing code from other files
We have been only including C standard libraries
MULTI-FILE You can also #include your own! (FUN!)
This allows us to join projects together
PROJECTS It also allows multiple people to work together on
projects out in the real world
WHAT ARE We will also often produce code that we can then
use again in other projects (that is all that the C
THEY? standard libraries are - functions that are useful in
multiple instances)
MULTI-FILE In a multi file project we might have:
(multiple) header file - this is the .h file that you
PROJECTS have been using from standard libraries already
(multiple) implementation file - this is a .c file, it
.H AND .C implements what is in the header file.
Each header file that you write, will have its own
implementation file
a main.c file - this is the entry to our program, we
header try and have as little code here as possible
file impleme
#include " .h"
ntation
file
.c
MULTI-FILE Typically contains:
function prototypes for the functions that will
PROJECTS be implemented in the implementation file
comments that describe how the functions will
.H be used
#defines
HEADER FILE the file basically SHOWS the programmer all
they need to know to use the code
header NO RUNNING CODE
file This is like a definition file
#include " .h"
MULTI-FILE This is where you implement the functions that you have
defined in your header file
PROJECTS

.C
IMPLEMENTATION

implementation
file
.c
MULTI-FILE This is where you call functions from that may exist in
other modules.
PROJECTS

MAIN.C
MULTI-FILE We will have three files:
header file - maths.h
PROJECTS implementation file - maths.c
#include "maths.h"
AN EXAMPLE main file - main.c
#include "maths.h"
MULTI-FILE
PROJECTS

AN EXAMPLE
HEADER FILE
MULTI-FILE
PROJECTS

AN EXAMPLE
IMPLEMENTATION
FILE (NOTE TO
INCLUDE THE
HEADER THAT WE
DEFINED!
MULTI-FILE
PROJECTS

AN EXAMPLE OF
MAIN THAT
DRIVES OUR
PROGRAM
MULTI-FILE To compile a multi file, you basically list any .c files you
have in your project (in the case of our example, we have
PROJECTS a maths.c and a main.c file):

COMPILING

The program will always enter in main.c, so there should


only be one main.c when compiling
Like an array, a linked list is used to store a collection
INTRODUCIN of the same data type
G A NEW So what's the point?
DATA Linked lists are dynamically sized, that means we
can grow and shrink them as needed - efficient
STRUCTURE for memory!
Elements of a linked list (called nodes) do NOT
LINKED LISTS need to be stored contiguously in memory, like an
array.
Unlike arrays, linked lists are not random access
data structures! You can only access items
sequentially, starting from the beginning of the
list.
HAVE A We hope that you all have a good rest and catch up
over the Flex Week time.
RESTFUL FLEX There are no formal classes next week!
WEEK! Help Sessions are still running, please check the
timetable
Forum will be monitored closely to help you with any
Assignment 1 queries
Feedback please!
I value your feedback and use to pace the lectures and improve your overall
learning experience. If you have any feedback from today's lecture, please
follow the link below. Please remember to keep your feedback constructive,
so I can action it and improve the learning experience.

https://forms.office.com/r/SdwfGte8MK
WHAT DID WE LEARN TODAY?

POINTERS MEMORY
howdy_pointer.c sizeof_demo.c
array_magic.c malloc.c
pointer_functions.c memory_fun.c
pointer_struct.c
CONTENT RELATED
QUESTIONS
REACH OUT Check out the forum

ADMIN QUESTIONS
[email protected]

You might also like