56
C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

Embed Size (px)

Citation preview

Page 1: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

C: Advanced Topics

Summer 2014

COMP 2130 Intro Computer Systems

Computing ScienceThompson Rivers University

Page 2: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 Data Representation 2

Course Objectives

The better knowledge of computer systems, the better programing.Computer System C Programming Language

Computer architectureCPU (Central Processing Unit)IA32 assembly language

Introduction to C language

Compiling, linking, loading, executing

Physical main memoryMMU (Memory Management Unit)

Virtual memory space

Memory hierarchyCache

Dynamic memory management

Better coding – locality

Reliable and efficient programming for power programmers(to avoid strange errors, to optimize codes, to avoid security holes, …)

Page 3: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 3

Course Contents

Introduction to computer systems: B&O 1 Introduction to C programming: K&R 1 – 4 Data representations: B&O 2.1 – 2.4 C: advanced topics: K&R 5.1 – 5.10, 6 – 7 Introduction to IA32 (Intel Architecture 32): B&O 3.1 – 3.8, 3.13 Compiling, linking, loading, and executing: B&O 7 (except 7.12) Dynamic memory management – Heap: B&O 9.9.1 – 9.9.2, 9.9.4 –

9.9.5, 9.11 Code optimization: B&O 5.1 – 5.6, 5.13 Memory hierarchy, locality, caching: B&O 5.12, 6.1 – 6.3, 6.4.1 –

6.4.2, 6.5, 6.6.2 – 6.6.3, 6.7 Virtual memory (if time permits): B&O 9.4 – 9.5

Page 4: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 4

Unit Learning Objectives

Use pointers and references. Use pointers for dynamic memory management. Use open(), read(), write(), close(), and FILE* functions to manipulate

files. Use user-defined data structures.

More coming

Page 5: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 5

Unit Contents

1. Pointers and Arrays

2. Input and Output

3. Structures

4. Self Referential structures

Page 6: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 6

1. Pointers and Arrays

Page 7: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 7

Pointers and Addresses

A pointer is a variable that contains the address of a variable. Pointers and arrays are very closely related.

int x = 1, y = 2, z[10];int *ip; /* ip is a pointer to int */ip = &x; /* ip now points to x */y = *ip; /* y is now 1 */*ip = 0; /* x is now 0 */ip = &z[1]; /* ip now points to z[1] */

Declaration of a pointer variable: * Reference operator: & Indirection operator (oac dereference operator): *

Page 8: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 8

int x = 1;int y = 2;int z[10];int *ip;

ip = &x;y = *ip;*ip = 0;ip = &z[1];

Varible name

value address

x 1 A

...

y 2 B

...

z E C

...

ip ? D

...

z[0] ? E

z[1] ? F

z[2] ?

...

z[3] ?

Page 9: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 9

int x = 1;int y = 2;int z[10];int *ip;

ip = &x;y = *ip;*ip = 0;ip = &z[1];

Varible name

value address

x 1 A

...

y 2 B

...

z E C

...

ip A D

...

z[0] ? E

z[1] ? F

z[2] ?

...

z[3] ?

Page 10: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 10

int x = 1;int y = 2;int z[10];int *ip;

ip = &x;y = *ip;*ip = 0;ip = &z[1];

Varible name

value address

x 1 A

...

y 1 B

...

z E C

...

ip A D

...

z[0] ? E

z[1] ? F

z[2] ?

...

z[3] ?

Page 11: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 11

int x = 1;int y = 2;int z[10];int *ip;

ip = &x;y = *ip;*ip = 0;ip = &z[1];

Varible name

value address

x 0 A

...

y 1 B

...

z E C

...

ip A D

...

z[0] ? E

z[1] ? F

z[2] ?

...

z[3] ?

Page 12: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 12

int x = 1;int y = 2;int z[10];int *ip;

ip = &x;y = *ip;*ip = 0;ip = &z[1];*ip = 5;

Varible name

value address

x 0 A

...

y 1 B

...

z E C

...

ip F D

...

z[0] ? E

z[1] ? F

z[2] ?

...

z[3] ?

Page 13: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 13

int x = 1;int y = 2;int z[10];int *ip;

ip = &x;y = *ip;*ip = 0;ip = &z[1];*ip = 5;

Varible name

value address

x 0 A

...

y 1 B

...

z E C

...

ip F D

...

z[0] ? E

z[1] 5 F

z[2] ?

...

z[3] ?

Page 14: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 14

Pointers and Function Arguments

How to write a function that swaps the values stored in two variables?

swap(a, b);...

void swap(int x, int y){

int temp;

temp = x;x = y;y = temp;

}

Is the above function correct? Why?

At assembly time, this function call will be expanded to create three variables in the stack area.

The stack pointer will be increased as the result.

The return statement is hidden.At assembly time, the return statement will be expanded

to delete three variables in the stack area. The stack pointer will be decreased as the result.

Page 15: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 15

swap(a, b);...

void swap(int x, int y){

int temp;

temp = x;x = y;y = temp;

}

Varible name

value address

a 1 A

...

b 2 B

...

x 1 C

y 2 D

temp ? E

...

At this moment

Page 16: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 16

swap(a, b);...

void swap(int x, int y){

int temp;

temp = x;x = y;y = temp;

}

Varible name

value address

a 1 A

...

b 2 B

...

x 2 C

y 1 D

temp 1 E

...

At this moment

Page 17: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 17

swap(a, b);...

void swap(int x, int y){

int temp;

temp = x;x = y;y = temp;

}

Varible name

value address

a 1 A

...

b 2 B

...

...

...

...

...

At this moment

Page 18: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 18

How to write a function that swaps the values stored in two variables?

swap(&a, &b);...

void swap(int *px, int* py){

int temp;

temp = ???;???;??? = temp;

}

Varible name

value address

a 1 A

...

b 2 B

...

px A C

py B D

tmp ? E

...

At this moment

Page 19: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 19

swap(&a, &b);...

void swap(int *px, int* py){

int temp;

temp = *px;*px = *py;*py = temp;

}

Varible name

value address

a 1 A

...

b 2 B

...

px A C

py B D

tmp 1 E

...

Page 20: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 20

swap(&a, &b);...

void swap(int *px, int* py){

int temp;

temp = *px;*px = *py;*py = temp;

}

Varible name

value address

a 2 A

...

b 2 B

...

px A C

py B D

tmp 1 E

...

Page 21: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 21

swap(&a, &b);...

void swap(int *px, int* py){

int temp;

temp = *px;*px = *py;*py = temp;

}

Varible name

value address

a 2 A

...

b 1 B

...

px A C

py B D

tmp 1 E

...

Page 22: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 22

swap(&a, &b);...

void swap(int *px, int* py){

int temp;

temp = *px;*px = *py;*py = temp;

}

Varible name

value address

a 2 A

...

b 1 B

...

...

...

...

...

Page 23: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C Programming 23

int *test;int number = 20;

test = &number;printf(“%d, %d, %p, %p\n”, number, *test, test, &test);

// the content of the var pointed by test

// the content of test*test = 30;printf(“%d, %d, %p, %p\n”, number, *test, test, &test); printf(“Enter an integer: ”);scanf(“%d”, &number); // the address of numberprintf(“%d, %d, %d, %p, %p, %p\n”, number, *test, *(&number),

test, &test, &number); // the content pointed by test // the content pointed // by the address of number // the content of test // the address of test // the address of number

Page 24: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 24

Can you write a function to read multiple integers into an array?

int data[10];getint(data, 10); // read 10 integers into data[]...

??? getint(???, ???){

??? // using scanf()

}

Page 25: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 25

Pointers and Arrays

Strong relation between and pointers

float *px; // px is ready to store an address.float x[10]; // x represents 10 float type variables, // x[0], x[1], ..., x[9], that are // alocated in cosecutive memory area. // x has the address of x[0].float y;

x[0] = 2; x[1] = 3; x[2] = 4; x[3] = 5; x[4] = 6; x[5] = 7;px = x; // the same data type?y = *px;printf(“%f, %f, %f\n”, x[0], *px, y); // ???px = &x[2];y = *(px+2);printf(“%f, %f, %f\n”, x[0], *px, y); // ???

Page 26: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C Programming 26

int number[10];printf(“%p\n”, &(number[0]));printf(“%p\n”, &(number[5]));printf(“%p\n”, number); // related to referenceprintf(“%p\n”, number + 5); // the address of number[5]

// not 5 * 4newval(number);...

void newval(int num[]) { num[0] = 5; ... }, orvoid newval(int* num) { *num = 5; *(num+1) = 10; num[2] = 20; ... }

int num[] and int *num are equivalent.

Page 27: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C Programming 27

int number[10];int *p, *q;

*p = 10; // Is it wrong?p = number;q = &number[0];number[0] = 2; number[1] = 9; number[2] = 5;printf(“%p, %p\n”, p, q);printf(“%d, %d, %d, %d\n”, *(p+1), p[1], *(q+1), q[1]);

Pointer variables and array variables can be used interchangeably.

Why do we need to use pointer variables?

Page 28: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C Programming 28

Do we really need to use pointers?

Dynamic memory management#include <stdlib.h>void *malloc(int size); // allocate size

bytes // and return the

addrvoid free(void *); // free the memory space...

int *p, n;scanf(“%d”, &n);// space for n-many integer variables.p = (int*)malloc(sizeof(int) * n); p[0] = 10; *(p+1) = 20; *(p+2) = 30; p++; *p = 4;

Page 29: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 29

Character Pointers

#include <string.h.>

gets(), puts()strcpy(), strlen(), strcmp(), strcat(), ...toupper(), ...

Page 30: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C Programming 30

char name[256], tmp[256];name[0] = ‘C’;name[1] = ‘O’;name[2] = ‘M’;name[3] = ‘P’;name[4] = ‘\0’; // it is very important.name[5] = ‘ ’;name[6] = ‘2’;name[7] = ‘1’;name[8] = ‘3’;name[9] = ‘0’;name[10] = ‘\0’; // it is very important.printf(“course number = %s\n”, name);printf(“%p\n”, name);printf(“course number = %s\n”, &(name[5]));scanf(“%s”, name); // not &name

sprintf(tmp, “course name is %s.”, name);

Page 31: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 31

3. Input and Output

Standard input from keyboard$ prog < infile input redirection$ otherprog | prog pipe

<stdio.h>

int getchar() int putchar(int c)

Page 32: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 32

Formatted input

int scanf (char *format, arg1, arg2, ...) // from stdin int sscanf (char *string, char *format, arg1, arg2, ...); // from string

The arguments must be references.

Page 33: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 33

File Access

#include <stdio.h>

FILE *in, *out; // FILE is defined in <stdio.h>in = fopen(“in_filename”, “r”); // mode: r, w, a, r+, w+,

a+if (in == NULL) ...out = fopen(“out_filename”, “w”);fclose(in);

fprintf(out, “format ...”, variables...);fscanf(...);fgets(...);int fseek(FILE*, long, SEEK_SET or SEEK_CURRENT or

SEEK_END); // move file position pointerint fwrite(void*, int memb_size, int no_memb, FILE*);int fread(void*, int memb_size, int no_memb, FILE*);

Page 34: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 34

int fputc(int, FILE*);int fputcs(char*, FILE*);int fgetc(FILE*);int fscanf(FILE*, char* format, ...);int fprintf(FILE*, char* format, ...);

Examples: A file copy program, using fopen(), fseek(), fwrite(), fread(), fclose(). Files containing student records

struct student { ... };struct student record;FILE *fp = fopen(“test”, “w+”); // read and write; file

truncated;fwrite(&record, sizeof(struct student), 1, fp);fread(&record, sizeof(struct student), 1, fp);

Page 35: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 35

How to obtain the current position:: long ftell(FILE*);

Page 36: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 36

Error Handling – Stderr and Exit

fprintf(stderr, char*, ...);exit(int); // non zero means error

Page 37: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C Programming 37

math.h Some MATH related functions

# include <math.h> double sqrt(double); double pow(double, double); double fabs(double); ...

Link with –lm -lm means libm.a, that contains

math utilities, is used $ gcc program3-5.c –lm

Page 38: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 38

Pointer Arrays: Pointers to Pointers

void f(int *x[13]); // 13 int* variablesvoid f(int (*x)[13]); // pointer to an array of 13 ints // equivalent to int x[][13]

Command-line arguments

int main(int argc, char *argv[]); argc the number of arguments argv[0] the program name, e.g., a.out argv[1] the first argument from the user E.g., $ ./a.out test this comp

argc: 4 argv[0]: “./a.out” argv[1]: “test

Page 39: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 39

Command-line arguments

int main(int argc, char *argv[]); argc the number of arguments argv[0] the program name, e.g., a.out argv[1] the first argument from the user E.g., $ ./a.out test this comp

argc: 4 argv[0]: “./a.out” argv[1]: “test

Page 40: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

Command Line Arguments

It is possible to pass some values from the command line in the C programs when they are executed.

These values are called command line arguments These are important as they can control the ‘C’ program from outside

instead of hard coding those values inside the code. The command line arguments are handled using main() function

arguments argc refers to the number of arguments passed, argv[] is a pointer array which points to each argument passed to the

program.

TRU-COMP2130 Introduction 40

Page 41: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

Example

#include <stdio.h>

int main( int argc, char *argv[] )

{ if( argc == 2 )

{ printf("The argument supplied is %s\n", argv[1]); }

else if( argc > 2 )

{ printf("Too many arguments supplied.\n"); }

else

{ printf("One argument expected.\n"); }

}

$./a.out testing

The argument supplied is testing

TRU-COMP3710 Introduction 41

Page 42: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

Structures

It is a way to have a single name referring to a group of a related values.

Structures provide a way of storing many different values in variables of potentially different types under the same name.

its design makes things more compact. Structs are generally useful whenever a lot of data needs to be grouped

together Example: a contact group may have {name, address, phone number,

and mobile number}

TRU-COMP3710 Introduction 42

Page 43: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

Example

struct database

{ int id_number;

int age;

float salary;

};

int main()

{ struct database employee; /* There is now an employee variable that has modifiable variables inside it.*/

employee.age = 22;

employee.id_number = 1;

employee.salary = 12000.21;

printf(“Employee ID = %d, Age = %d and Salary = %7.2f”, employee.id, employee.age, employee.salary);

}

TRU-COMP3710 Introduction 43

Page 44: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 44

2. Structures

User-defined data structurestruct student_rcd { // class without methods in Java

int student_number;char name[128];...

};...

struct student_rcd record[10], *rp;struct student_rcd test; // how to declare a struct variable

test.student_number = 10; // how to access a memberprint_rcd(test);read_rcd(&test);record[0].student_number = 5;

Page 45: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 45

void print_rcd(struct student_rcd rcd){ printf(“Number: %d\n”, rcd.student_number); printf(“Name: %s\n”, rcd.name); // name is an array. // not &(rcd.name)}

void read_rcd(struct student_rcd *rcd){ printf(“Enter number: “); scanf(“%d”, &(rcd->student_number)); // reference rqd printf(“Enter name: “); scanf(“%s”, rcd->name); // name is an array. // not &(rcd->name)}

Page 46: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 46

Self-Referential Structures

struct tnode { /* the tree node: */ char *word; /* points to the text */ int count; /* number of occurrences

*/ struct tnode *left; /* left child */ struct tnode *right; /* right child */ struct tnode *parent;};

struct tnode root;root.left = (struct tnode *)malloc(...);

Page 47: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 47

Typedef

typedef int Length; // Now Length is a data type.typedef char *String; // Now String is a data type.typedef struct tnode { /* the tree node: */ char *word; /* points to the text */ int count; /* number of occurrences */ struct tnode *left, *right; /* children */ struct tnode *parent;} Treenode; // Now Treenode is a data type....

Length len, maxlen;Length *lengths[];String p, lineptr[MAXLINES];Treenode tnode1;

Page 48: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

Union

A union is a special data type available in C that enables you to store different data types in the same memory location like structures

The main difference is that a union may have many members, but only one member can contain a value at any given time.

Unions provide an efficient way of using the same memory location for multi-purpose.

TRU-COMP3710 Introduction 48

#include <stdio.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; printf( "data.i : %d\n", data.i); return 0; }

Page 49: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 49

Dynamic Memory Allocation

struct Student { char name[128]; int number; Student *next;};typedef struct Student Student;

Student *head = null; // importantStudent *new, *tmp;

new = create_student(); // create a record, read data from the user, // store them into the record

add_student(head, new); // add the new record at the end of the list

tmp = find_student(head, 968374); // find the record whose number is ..printf(“%d: %s\n”, tmp->number, tmp->name); // print the record

delete_student(head, 968374);

NameNumbernext

NameNumbernext

NameNumbernext

Head

null

Page 50: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

Allocation functions

Malloc() Calloc() Free()

TRU-COMP2130 Introduction 50

Page 51: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

Malloc()

The name malloc stands for "memory allocation".

The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form.

Syntax of malloc()

ptr=(cast-type*)malloc(byte-size)

ptr is pointer of cast-type.

The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.

Example: ptr=(int*)malloc(100*sizeof(int));

will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory.

TRU-COMP2130 Introduction 51

Page 52: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

Calloc()

The name calloc stands for "contiguous allocation". The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.

Syntax of calloc()

ptr=(cast-type*)calloc(n,element-size);

This statement will allocate contiguous space in memory for an array of n elements.

Example:

ptr=(float*)calloc(25,sizeof(float));

This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.

TRU-COMP2130 Introduction 52

Page 53: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

Free()

Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The programmer must use free() explicitly to release space.

syntax of free()

free(ptr);

This statement cause the space in memory pointer by ptr to be deallocated.

TRU-COMP2130 Introduction 53

Page 54: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

realloc

If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory size previously allocated using realloc().

Syntax of realloc()

ptr=realloc(ptr,newsize);

Here, ptr is reallocated with size of newsize.

TRU-COMP2130 Introduction 54

Page 55: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 55

... create_student( ... ) // create a record, read data from the user,{ // store them into the record Student *new = ( ... )malloc( ... ); scanf(“%s”, ...) // read name scanf(“%d”, ...) // read number new->next = null; // very important; (*new).next = null

return ...;};

... add_student(... head, ... new) // add the new record at the end of the list{ Student *tmp; if (head == null) // when there is no record yet head = new;

else { while((*tmp).next != null) // move to the last record tmp = (*tmp).next; // You cannot use array syntaxes (*tmp).next = new; // because the Student objects were not } // consecutively created.

return;}

Page 56: C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

TRU-COMP2130 C: Advanced Topics 56

... find_student(... head, ... no) // find the record{ Student *tmp; tmp = head; while(tmp != null) { if ((... == no) break; tmp = ...; }}

... delete_student(... head, ... no){...}