Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
57 views

06 C Programming 2

Here are the key points about pointers and functions: - Call by value: Function gets copies of the arguments. Changes made inside function don't affect original variables. - Call by reference: Function gets addresses of arguments. Changes made inside function affect original variables. - To pass by reference in C, arguments must be pointers that point to the original variables. Any changes made through the pointers affect the original variables. - To update original variables through a function, their addresses/pointers must be passed as arguments rather than the variables themselves. So in summary, pointers allow passing addresses of variables to functions rather than copies, enabling changes to original variables through the pointers inside the function.

Uploaded by

Darwin Vargas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

06 C Programming 2

Here are the key points about pointers and functions: - Call by value: Function gets copies of the arguments. Changes made inside function don't affect original variables. - Call by reference: Function gets addresses of arguments. Changes made inside function affect original variables. - To pass by reference in C, arguments must be pointers that point to the original variables. Any changes made through the pointers affect the original variables. - To update original variables through a function, their addresses/pointers must be passed as arguments rather than the variables themselves. So in summary, pointers allow passing addresses of variables to functions rather than copies, enabling changes to original variables through the pointers inside the function.

Uploaded by

Darwin Vargas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

ì

Computer Systems and Networks


ECPE 170 – Dr. Pallipuram– University of the Pacific

C Programming 2
The slides are credited to Dr. Shafer
2

ì
C-Strings (Arrays of Characters)
Computer Systems and Networks Fall 2021
3

C Strings

ì There is no such thing as a “string” in C!

ì What do you get? An array of characters


ì Terminated by the null character '\0'

ì Must manipulate element by element…


ì Not enough room in the array? Need a bigger array

Computer Systems and Networks Fall 2021


4

Arrays of Characters

ì char phrase[]="Math";

phrase

phrase[0] phrase[1] phrase[2] phrase[3] phrase[4]

M A T H \0

Null terminator character


(End of string)
Computer Systems and Networks Fall 2021
5

Arrays of Characters

ì char phrase[8]="Math";
phrase

phrase[0] phrase[1] phrase[2] phrase[3] phrase[4] phrase[5] phrase[6] phrase[7]

M A T H \0 ??? ??? ???

printf("%s\n", phrase); Prints until it reaches


the \0 character!
Computer Systems and Networks Fall 2021
6

Helpful Library for Character Arrays

ì #include <string.h>

ì Useful functions
ì strcpy - String copy
ì strcmp - String compare
ì strlen - String length
ì strcat - String concatenate

Computer Systems and Networks Fall 2021


7

String Copy

ì char phrase1[] = "Math";

ì char phrase2[8];

ì strcpy(phrase2, phrase1);
phrase phrase1[0] phrase1[1] phrase1[2] phrase1[3] phrase1[4]

1
M A T H \0

phrase phrase2[0] phrase2[1] phrase2[2] phrase2[3] phrase2[4] phrase2[5] phrase2[6] phrase2[7]

2
M A T H \0 ??? ??? ???
Computer Systems and Networks Fall 2021
8

String Concatenation

ì char phrase1[8] = “Comp”;

ì char phrase2[] = “Sci”;

ì strcat(phrase1, phrase2);
phrase phrase1[0] phrase1[1] phrase1[2] phrase1[3] phrase1[4] phrase1[5] phrase1[6] phrase1[7]

1
C O M P S C I \0

phrase phrase2[0] phrase2[1] phrase2[2] phrase2[3]

2 You cannot do this:


S C I \0 phrase2=
phrase1+phrase2;
Computer Systems and Networks Fall 2021
9

ctype Library

ì Useful for character manipulation

ì #include <ctype.h>

ì toupper(char) / tolower(char) – Converts


character to uppercase or lowercase
ì Example:

char c = toupper('a');
printf("%c", c); // A

Computer Systems and Networks Fall 2021


10

ctype Library

ì isalpha(char) – Is the character a letter?

ì isdigit(char) – Is the character a number 0-9?

ì isspace(char) – Is the character whitespace?


(space or newline character)

ì ispunct(char) – Is the character punctuation?


(technically, a visible character that is not whitespace, a
letter, or a number)

ì … and several other variations

Computer Systems and Networks Fall 2021


11

ì
File I/O
Computer Systems and Networks Fall 2021
12

File I/O Functions

ì fopen – opens a text file

ì fclose – closes a text file

ì feof – test for end-of-file

ì fgets – reads a string from a file, stopping at EOF or


newline
ì fwrite – writes array of characters to a file

ì fgetc – reads a character from a file

ì fputc – prints a character to a file

Computer Systems and Networks Fall 2021


13

#include <stdio.h>

int main()
{
FILE *ptr_file;
char buf[1000];

ptr_file = fopen("input.txt","r");
if (!ptr_file)
return 1;

while (fgets(buf,1000, ptr_file)!= NULL)


printf("%s", buf);

fclose(ptr_file);
return 0;
}

Computer Systems and Networks Fall 2021


14

Pointer Arithmetic

ì Only addition and subtraction are allowed with


pointers

ì All pointers increase and decrease by the length of


the data-type they point to

ì Example
ì If an integer pointer, iptr holds address 32, then
after the expression iptr++, iptr will hold 36
(assuming integer is 4 bytes).

Computer Systems and Networks Fall 2021


15

Problem 1
The name of the array is actually a pointer pointing to the first element of the array.

Subscript [0] [1] [2] [3] [4]


Value 5 6 4 8 2
Address 65528 65532 65536 65540 65544

Consider an integer array named array.


printf(“\n %u:”, array); //prints 65528
printf(“\n %u:”, array+2); //prints 65536
printf(“\n %u:”, *(array+1));
//literally translates to array[1]. Prints 6

printf(“\n”, %u:”, array+3); //prints?______


printf(“\n”, %u:”, *(array+3)); //prints?______ P1
Computer Systems and Networks Fall 2021
16

Pointers and Functions:


Call by value vs. Call by reference
Call by value Call by reference (pointer)
main(){ main(){
a=5,b=6; a=5,b=6;
update(a,b); update(&a,&b);
printf(“%d”,a); printf(“%d”,a);
} }

update(int a, int b) { update(int *a,int *b) {


a=a-b; *a=*a-*b;
} }

These are just copies. Modification to actual variable


No change to original
variables
Computer Systems and Networks Fall 2021
17

ì
Dynamic Memory Management
Computer Systems and Networks Fall 2021
18

Memory Allocation with malloc()

ì #include <stdlib.h>

ì void * malloc(int size)


ì Allocate region in memory (aka “new”)
ì Argument: Size of region in bytes to allocate
ì Return value: Pointer to the region

ì void free(void * ptr)


ì De-allocate region in memory (aka “delete”)
ì Argument: Pointer to the region

Computer Systems and Networks Fall 2021


19

Memory Allocation with malloc()

ì void * calloc(int count, int size)


ì Basically the same as malloc!
ì Imagine you want an array of elements…
ì Argument 1: # of elements to allocate
ì Argument 2: Size of each element in bytes
ì Return value: Pointer to the region

Computer Systems and Networks Fall 2021


20

Memory Allocation with malloc()

ì void * realloc(void *ptr, int size);


ì Resize a dynamic region of memory
ì Note that it might move to a new address!
ì Argument: Pointer to the original region
ì Argument 2: Desired size in bytes of new region
ì Return value: Pointer to the new region
ì It might be at the same address if you made it smaller
ì It might be at a new address if you made it larger

Computer Systems and Networks Fall 2021


21

Malloc – 1D

int *array; //array of integers

array (pointer variable)


value: ???? 60
pointer addr: 32

array = (int *)malloc(sizeof(int)*5);

address: 60 64 68 72 76
value: array[0] array[1] array[2] array[3] array[4]

Computer Systems and Networks Fall 2021


22

Malloc – 2D
Allocate 4x5 integers (Hint for lab 4)
int **array; //a double pointer

array = (int **)malloc(sizeof(int *)*4);

for(i=0;i<4;i++)
array[i] = (int *)malloc(sizeof(int)*5);

array of ints
array of ints
array of ints

array of ints

an array of integer pointers

Computer Systems and Networks Fall 2021


23

Malloc – 3D
int ***array; //a triple pointer

a ‘cuboid’ of integers
an array of a matrix of
double pointers single pointers

Computer Systems and Networks Fall 2021


24

Problem 2

ì Dynamically allocate space for a 3-D color image of


width, w; height, h; color channel, c. Any pixel is
accessed as image[height][width][c].

P2
Computer Systems and Networks Fall 2021
25

ì
Memory Management Internals
Computer Systems and Networks Fall 2021
26

Memory Management

ì Who implemented malloc()?

ì C Standard Library: #include <stdlib.h>

ì There are different C Standard Library


implementations!
ì Android: Bionic
ì Apple: BSD-based / Proprietary
ì Microsoft: Proprietary C Runtime Library
ì Linux: GNU C Library (glibc)
http://www.gnu.org/software/libc/

Computer Systems and Networks Fall 2021


27

Memory Management

ì Where does the malloc() memory come from?

ì The Heap:
ì A region of memory for dynamic memory allocation
ì Per-process – each program gets its own heap
ì Managed by malloc() and related functions
ì Different from the stack, which is for static variables
(known at compile-time)

Computer Systems and Networks Fall 2021


28

Memory Management

ì malloc() outline:

1. Call malloc() and request memory

2. malloc() checks existing heap size


ì Sufficient? Update bookkeeping to mark space as
“used” and return address to your program
ì Insufficient?
1. Call operating system via brk()/nmap() to grow
the heap (plus a little extra for future requests)
2. Update bookkeeping and return address to your
program

Computer Systems and Networks Fall 2021


29

Memory Management

ì Why do we need to call free() after calling


malloc()?
ì Memory leak
ì malloc() cannot re-use that space ever, because
its internal bookkeeping still thinks that region is
used
ì Will only be recovered upon terminating program
ì Operating system wipes out all the memory allocated
to your process (stack, heap, etc…)

Computer Systems and Networks Fall 2021


30

Memory Management
0xFFFFFFFFFFFFFFFF (32 or 64 bit)
ì OS creates virtual
memory space for
process when started

ì Region is huge (full 32 Virtual Memory Space


or 64 bit space)
for new process
ì Not fully mapped to
physical memory
ì Otherwise you
could only fit 1
program in memory

0x0000000000000000
Computer Systems and Networks Fall 2021
31

Memory Management
0xFFFFFFFFFFFFFFFF (32 or 64 bit)
ì OS loads in the
program from
disk

ì “Text” region
ì Program code

ì “Data” region
ì Program fixed
data Data (Program data)

Text (Program code)

0x0000000000000000
Computer Systems and Networks Fall 2021
32

Memory Management
0xFFFFFFFFFFFFFFFF (32 or 64 bit)
ì Stack created to Stack
track program
function calls
and local
variables

Data (Program data)

Text (Program code)

0x0000000000000000
Computer Systems and Networks Fall 2021
33

Memory Management
0xFFFFFFFFFFFFFFFF (32 or 64 bit)
ì Heap created to Stack
store dynamic
memory from
malloc()and
(Unused / unmapped virtual memory)
related functions

ì Not to scale –
this unused Heap
region is huge!
Data (Program data)

Text (Program code)

0x0000000000000000
Computer Systems and Networks Fall 2021
34

Memory Management
0xFFFFFFFFFFFFFFFF (32 or 64 bit)
ì Program starts Stack
running

ì malloc()
allocates some (Unused / unmapped virtual memory)
memory

Heap

Data (Program data)

Text (Program code)

0x0000000000000000
Computer Systems and Networks Fall 2021
35

Memory Management
0xFFFFFFFFFFFFFFFF (32 or 64 bit)
ì Original heap Stack
space eventually
fills up
(Unused / unmapped virtual memory)
ì malloc()
requests New
space
additional space Heap
from the kernel
by using brk()
system call Data (Program data)

Text (Program code)

0x0000000000000000
Computer Systems and Networks Fall 2021
36

Memory Management
0xFFFFFFFFFFFFFFFF (32 or 64 bit)
ì free() Stack
deallocates
blocks from the
heap (Unused / unmapped virtual memory)

Heap

Data (Program data)

Text (Program code)

0x0000000000000000
Computer Systems and Networks Fall 2021
37

Memory Management
0xFFFFFFFFFFFFFFFF (32 or 64 bit)
ì Program Stack
terminates

ì OS expunges (Unused / unmapped virtual memory)


entire virtual
address space
ì Everything is Heap
deleted

Data (Program data)

Text (Program code)

0x0000000000000000
Computer Systems and Networks Fall 2021
38

Buffer Overflow Vulnerability

ì What is a buffer overflow bug?


ì char buf1[8]="";
char buf2[8]="";
strcat(buf1, "excessive");

ì End up overwriting two characters beyond buf1!

Computer Systems and Networks Fall 2021


39

Buffer Overflow Vulnerability

ì Why is a buffer overflow bug dangerous?

ì What is beyond my buffer in memory?


ì Other variables and data? (probably buf2)
ì The stack? (further out)
ì The return address to jump to after my function
finishes?

ì If app is running as administrator, attacker now has


full access!

Computer Systems and Networks Fall 2021


40

Memory Management

ì Limitless opportunities in C for errors regarding memory


L
ì Forgetting to free() some dynamic memory
ì Trying to free() dynamic memory more than once
ì Losing a pointer to dynamic memory (memory is “lost”)
ì Accessing array elements past the end of the array
ì Mis-calculating array pointers that miss their desired
target

ì Will learn a tool (Valgrind) in Lab 5 to analyze your


program and detect / trace errors

Computer Systems and Networks Fall 2021


41

What’s the Error?

char *a = malloc(128*sizeof(char));
char *b = malloc(128*sizeof(char));
b = a;
free(a);
free(b);

http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html

Computer Systems and Networks Fall 2021


42

What’s the (Potential) Error?

char *a = malloc(128*sizeof(char));

dataLen = <some value...>

// Copy “dataLen” bytes


// starting at *data to *a
memcpy(a, data, dataLen);

http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html
Computer Systems and Networks Fall 2021
43

What’s the Error?

ptr = (char *) malloc(strlen(string_A));


strcpy(ptr, string_A);

http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html

Computer Systems and Networks Fall 2021


44

What’s the Error?


int *get_ii()
{
int ii = 2; // Local stack variable
return &ii;
}
main()
{
int *ii;
ii = get_ii();
... Do stuff using ii pointer
}

http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html
Computer Systems and Networks Fall 2021
45

http://xkcd.com/371/

Computer Systems and Networks Fall 2021


46

Memory Management

ì What’s a NULL pointer?


ì Pointer value is 0x000000000
ì Meaning is that the pointer is not pointing anywhere

ì What happens if you dereference a NULL pointer?


ì Telling the computer to read from (or write) to the
value stored in the pointer, which is 0x000000000
ì Behavior undefined and generally unpleasant on
various computer systems

Computer Systems and Networks Fall 2021


47

Memory Management

ì “Segfault” = Segmentation Fault

ì Your program tried to read or write a virtual memory


address that is not allowed
ì Tried to read memory outside of program bounds?
ì Tried to write read-only memory regions? (used for
program data)

ì “Segmentation” was the name of an old system (back


before Intel 386 processors) used to divide physical
computer memory into many virtual address regions,
one per application process
ì The Segfault name stuck even though we now use paging
to manage virtual memory

Computer Systems and Networks Fall 2021


48

ì
Structures
Computer Systems and Networks Fall 2021
49

Structures
struct database
{
Useful way to group
int id_number; related variables!
int age;
float salary;
};

int main()
{
struct database employee;
employee.age = 22;
employee.id_number = 1;
employee.salary = 12000.21;
}
Computer Systems and Networks Fall 2021
50

Problem
Declare a structure called board that contains:
• a double character pointer matrix
• two integer variables height and width denoting the
number of rows and columns in the matrix.

Inside main, do the following:

1. Create a structure object called myboard,


initialize matrix to NULL, set height to 7 and width to 7
2. Dynamically allocate matrix to hold height x
width elements
P3
Computer Systems and Networks Fall 2021
51

Problem
Continue with the code from Problem 3.

free() is actually a reverse operation of malloc. The steps you use for free are opposite
of the steps for malloc. Free the dynamically allocated 2D matrix you created in
Problem 3.

Computer Systems and Networks Fall 2021


52

You’re ready to

for Lab 4!
Computer Systems and Networks Fall 2021

You might also like