Anda di halaman 1dari 18

LO03: From C to Intermediate

C++: Memory and Object


Manipulation
Prof Dr Ir Wan Azhar Wan Yusoff
Faculty of Manufacturing Engineering
March 2018

Outcomes
01 Physical versus Virtual Memory
02 Virtual Memory Organization
03 Heap Memory
04 C Pointer versus C++ Reference http://notebooks.com/2013/1
0/29/how-to-choose-the-
05 C Array versus C++ Vector right-memory-for-your-
notebook/

06 Function overload
07 Function pointer
08 C++ File I/O
01 Physical Versus Virtual Memory
(1) Each program (our .exe program) is
called a process with an ID. Each
process has his own memory
organization i.e. has collection of
instructions (code) and data. This
organization is called virtual
memory.
(2) Windows Memory Manager maps
each process virtual memory to
the actual physical memory.
(3) Thus each process occupies
different physical addresses
although each process has similar
virtual memory address.
(4) For example, both processes can
have the same virtual memory
address; but will have different
location in physical address.
(5) Look at the size of virtual memory
– for 64-bit addressing, the
memory starts at 0x00000000 to
0xFFFFFFFF.
01 Physical Versus Virtual Memory

(1) I had created two similar programs and print out the
address of an integer and a double.
(2) I had ran the program simultaneously. Both variables Two processes are running
share the same addresses. on Windows OS at one
(3) The address is the virtual memory address. time. Both variable a and
(4) The operating system maps the virtual address into d have the same address.
the actual physical address (RAM).
(5) Can you find the process ID?
02 Virtual Memory

Virtual memory organization:


(1) Text section. The program instructions are
located here. It is supposed to be a read
only memory section.
(2) Data section. This section consists of
initialized data (int a = 12;) and uninitialized
data ( int b;).
(3) Stack section. This section allocate data
when functions are called. Example the
function int add(int a, int b), the variable a
and b are created in the stack. It is created
when the function add() is called and is
deleted when the function exits.
(4) Stack grows downward (called push). When
the functions exit, it removes the data
(called pop);
(5) Heap section. This section is reserved for
dynamic memory allocations. When
malloc() is called in the program for more
memory, the memory is created in this
section. To remove the memory, free() is
called.
(6) Remember, the memory address is only
virtual address. All program use this
memory model.
02 Virtual Memory
03 Heap Memory
ID[num -1]
.

(1) C heap memory management uses malloc(),


calloc() and free().
(2) In our example, we need memory based on
user demands. We called this dynamic
memory allocation.
(3) In our example, we want to assign student ID
in a class. How many should we reserve? We
have to ask the user.
(4) First, we create an int pointer, ID. ID only has
one int address element. Then we ask for
number of students. Next, we call malloc() to
create the number of bytes needed. We also
need to cast to integer pointer since our ID is
an int pointer. Lastly, we assign the ID. .
(5) The memory pointed by ID is created on the
heap virtual memory section.
(6) We have to call free() in order to reclaim the ID[2] 2
memory in the heap. Otherwise, possible
memory leak.
(7) This is only creating new memory for integer. ID[1] 1
We can also create new memory for struct,
or even an array of struct!
ID[0] 0
&ID
04 C Pointer versus C++ Reference
(1) Computer operates based on stored data in
memory or register. Computer stores data in
an address system. For every data, there is a
Address Contents
corresponding address where the data is 0xFF3D 127
located. 0
(2) To access (read) a data or to change (write) a int a = 127
data, we need the location of that data i.e. 0
the address. 0
(3) In programming, we store the address in a
pointer. Therefore, pointer is a variable that
contains an address of a data.
(4) A pointer must have type because the type
determine the size of the data. For example,
integer pointer is an address of a 4 bytes int* ptrA = &a 0xFF23 0xFF3D
data whereas the double pointer in an
address of 8 bytes data.
(5) However, the pointer size is the same for
both integer pointer or a double pointer. The
pointer size is 4-bytes for a 32-bit system.
04 C Pointer versus C++ Reference
(1) In programming, we pass data to function
and a return value from a function. A copy of value 10
(2) We have two choices when passing data: was assigned to
(1) We pass the content of the data. This stack variable int a.
is called pass-by-value. This stack variable
(2) We pass the address of the data. This has nothing to do
is called pass-by-reference. with the main
(3) If we pass the content of the data (by-value), variable int a.
the receiving function knows the value of the
data but does not know the location of the
data.
(4) If we pass the address of the data (by-
reference), the receiving function knows
both the content and the location of the
data. The address of int
(5) If we pass by address, the function can a was sent to the
read/write the variable whereas if we pass stack pointer int a.
by value the function can only receive a copy Now, the stack
of the value. pointer int a can
(6) C uses pointer to pass-by-reference while write and read the
C++ uses reference to pass-by-reference. main int a.
(7) If we know the address, indirection operator
can access the content. C uses * operator as
indirection.
04 C Pointer versus C++ Reference
(1) A reference is an alias to a variable.
Reference declaration-definition:
int a = 5;
int &refA = a;
(2) Differences between Reference and
C++ pass by value.
Pointer: The variable a in
(1) Reference cannot have NULL value. the main function
(2) Reference can be initialized to one does not change.
variable only and cannot change to
another variable. Pointers can point
to any address.
(3) We must initialize the reference
that we have created. Pointers do
not have to be initialize
immediately.
(3) Frankly, I don’t see any advantage of using C++ pass by
reference. Just use pointer. That’s why we reference. The
claim that we are a C/C++ programmer! address operator is
(4) Maybe the only advantage I can see is the on the receiving
avoidance of indirection when we use side. Compare to
pointers.
pinter, there is no
(5) Which one is better? I will stick to pointers.
But, we must know both! need for
indirection!
05 C Array versus C++ Vector
(1) C++ Vector is an alternative to C array. Use
<vector> standard library.
(2) Vector is a dynamic size array with various
support functions. Array size must be defined
at compile time. Vector size is growing at run-
time.
(3) We can start with an array of one element and
grow the size as needed. We can also delete
an element at one time.
(4) Important “support functions” for vector are:
(1) size() – get vector size
(2) resize(n) – change the size of vector to
size n.
(3) push_back() – add element at the end
(4) pop_back() – delete element at the end
(5) [] – access element operator. Also, we
can use at().
(5) Vector is dynamic. We don’t have to set the
size during the design. In contrast, we have to
fix the array size when designing the program.
(6) We can initialize vector like: vector<int> a(5,0)
which means we declare int vector with 5
elements and with value 0.
05 C Array versus C++ Vector
(1) We can implement vector as stack data structure
whereby the last element enter is the first element
out. LIFO – Last In First Out.
(2) “The most common uses of a stack are:
1) To reverse a word - Put all the letters in a
stack and pop them out. Because of LIFO
order of stack, you will get the letters in
reverse order.
2) In compilers - Compilers use stack to
calculate the value of expressions like
2+4/5*(7-9) by converting the expression
to prefix or postfix form.
3) In browsers - The back button in a browser
saves all the urls you have visited https://www.programiz.com/dsa/stack
previously in a stack. Each time you visit a
new page, it is added on top of the stack.
When you press the back button, the
current URL is removed from the stack and
the previous url is accessed.”

Quoted from https://www.programiz.com/dsa/stack.


05 C Array versus C++ Vector

(1) C++ string is an alternative to char* or char [] in C. Use <string>.


(2) String variable is a collection of characters in a vector instead of an array.
(3) Few advantages
(1) Can assign to new string without string copy function.
(2) Can use vector operations like push_back(), pop_back() etc.
(4) Use string whenever possible. But, you must understand char* because many serious programs use
char*.
06 C++ Function Overload

(1) C++ can have same function name


provided the function arguments
or the function return value are
different.
(2) Example:
(1) int foo(void)
(2) void foo(int a)
(3) double foo(double a, double
b)
(3) All the functions above are having
the same name i.e. foo(). But they
have different arguments or
different return value.
(4) Functions with different arguments
but with the same name is an
overloading functions.
(5) This is important when we want to
initialize an object data type i.e.
the construction function.
07 C/C++ Function Pointer
(1) We can also make pointer to a
function.
(2) Since a function is just a memory
allocation for codes, we can save its
top address just like we save the
address of a variable.
(3) In our example here, we have a
function foo() that just takes a string
and display on a screen.
(4) We then make a function pointer
ptrFoo() that saves the address of
function foo();
(5) Then, we can either display string
using foo() or *ptrFoo(), just like we
are doing with variables!
(6) What is the size of ptrFoo()?
08 C++ File Input Output

(1) C++ File I/O is using <fstream>


Reading and
standard library whereas C File I/O
writing text file
uses <stdio.h>. -
(2) There are two types of I/O to file Character I/O
data: text and binary.
(3) “Text files store data as a sequence
of characters; binary files store data
as they are stored in primary
memory.” Forouzan and Gilberg
2001.
(4) Formatted input output and string is Reading and
a text file. writing binary
(5) We read-write binary file block by file
block of data whereas we usually - Block I/O
read-write text file either character
by character or line by line.
(6) In our example, the number “768” is
stored as character “7”, “6” and “8”
in text file. In binary file, the number
is stored as number 768.

Forouzan and Gilberg. Computer Science. A


structured Programming Approach Using C. Second
Edition. Brooks/Cole Thomson Learning. 2001.
Please read Chapter 13, Binary Files.
08 C++ Text File
(1) C++ File I/O is using <fstream> standard
library whereas C File I/O uses <stdio.h>.
(2) First, we define the file as either for input or
output. Here we use ofstream type for
output and ifstream type for input.
(3) We can then write data to file using myFile
<< operator just like we do with cout <<. It
looks easy.
(4) We can read data to file by using myFile >>
jut like cin >>. Remember, we can
know the size of a
(5) The myFile.eof() is important for reading vector!
data. It is the end of the file.
(6) When we read and write data from or to file,
we read and write line by line until end of
file. This is the easiest way for text input-
output. But we must know how the data is
arranged in the file.
(7) In our case, we write and read line by line
using vectors and organize the data in three
columns: id, cpa and program.
(8) That is why when we open the file and read
the text file, we read line by line with each
line consists of id, cpa and program.

Here I forgot to close myInfile() because


I am a human being!
08 C++ Text File

(1) C++ stream will create a new file and write


the data. However, if the file is an existing
file, it will delete the contents and add
new data to the file.
(2) If we want to add data at the end of
existing file, we can open file as append.
Append means continue to write data at
the end and do not delete the existing
data.
(3) In our case, the syntax is ofstream
myOutFile(filename, ios::app);
(4) ios::app specify that we want to append.
(5) Remember the :: is the scope operator. So
in this case ios::app is the input-output Append
scope of append. please!
(6) Do not forget to close the file once we are
done!
08 C++ Binary File
(1) Instead of saving as text file, we can also
save data to file using binary format.
(2) The difference is critical for number: if we
save number 123 as text, we will save
character ‘1’, character ‘2’ and character
‘3’. Each is one byte. But if we save the
number in binary format, the computer
will treat is an integer number of value
123. This is 4 bytes.
(3) In our program, we write the vector id, Here, we use
cpa and program in block as binary file. different
We have to cast to (char*) and the syntax. We
address of the variable is used. use fstream
(4) We must read in the right order we write! type and
specify input
(5) Sometimes, we prefer to save in text file or output and
so that we can view the contents of the the type of
file using text editor. If you save data in file.
binary format, you will see garbage
number when viewing from text editor.
(6) Advantage of binary format is block read
write. We can just read or write the entire
data in one statement – without the need
of a loop. When we save structure data
type, binary is necessary.

Anda mungkin juga menyukai