0% found this document useful (0 votes)
5 views13 pages

Lab4 ComputerSystem Programming

The document outlines a laboratory exercise focused on dynamic memory allocation and linked lists in C programming. It includes objectives such as defining data structures, managing memory dynamically, and implementing linked lists for student records and polynomial expressions. The lab consists of multiple experiments that guide students through practical coding tasks, emphasizing memory management techniques and data structure manipulation.

Uploaded by

kiennguyen050776
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)
5 views13 pages

Lab4 ComputerSystem Programming

The document outlines a laboratory exercise focused on dynamic memory allocation and linked lists in C programming. It includes objectives such as defining data structures, managing memory dynamically, and implementing linked lists for student records and polynomial expressions. The lab consists of multiple experiments that guide students through practical coding tasks, emphasizing memory management techniques and data structure manipulation.

Uploaded by

kiennguyen050776
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

Laboratory 4:

DYNAMIC MEMORY ALLOCATION AND LINKED LISTS

OBJECTIVES

 Learn how to define and use struct, union, and enum to represent and organize data

effectively. Besides, understand the difference between struct and union in terms of

memory layout and usage.

 Understand how memory is allocated and managed dynamically in C using malloc,

calloc, realloc, and free.

 Practice working with arrays and structures through both static and dynamic memory

allocation.

 Develop skills in creating, linking, traversing, and freeing nodes in a singly linked list.

 Apply pointers and pointer-to-pointer techniques to manipulate dynamically

allocated data structures.

 Build modular C programs that manage student records and polynomial expressions

using dynamic memory and linked lists.

PREPARATION FOR LAB 4

 Finish Lab 0 at home.

REFERENCE

Department of Electronics Page | 1

Computer System and Programming Laboratory (Advanced Program)


Laboratory 4:
DYNAMIC MEMORY ALLOCATION AND LINKED LISTS
EXPERIMENT 1

Objective: Learn how to define and use the struct data type and typedef in C.

Requirements:

- Define a structure Student that includes the fields: student ID (string with maximum

10 characters), full name (string with maximum 100 characters), cumulative GPA on

a 4.0 scale (floating-point number). Use typedef to simplify the type name.

- Write a function: void enterStudent(Student *sd)

This function prompts the user to input information for a student.

- Write a function: void printStudent(Student sd)

This function prints the student’s information to the screen.

- In the main() function, declare a variable of type Student, then call the input and output

functions to test the program.

Example:

Input:

Enter student information:

- Student ID: 2400000

- Full name: Nguyen Van A

- GPA: 4.0

Output:

--- STUDENT INFORMATION ---

[2400000] Nguyen Van A - GPA: 4.0

Department of Electronics Page | 2

Computer System and Programming Laboratory (Advanced Program)


Laboratory 4:
DYNAMIC MEMORY ALLOCATION AND LINKED LISTS
Check:

1. Why must the function enterStudent use a pointer and the “->” operator, while the

function printStudent only needs to pass the structure by value and use the “.”

operator?

2. Use the sizeof(Student) operator to print the size of the structure. What do you observe

about the memory size of the struct? Explain your result.

Department of Electronics Page | 3

Computer System and Programming Laboratory (Advanced Program)


Laboratory 4:
DYNAMIC MEMORY ALLOCATION AND LINKED LISTS
EXPERIMENT 2

Objective:

- Understand the difference in memory allocation between struct and union in C.

- Apply enum to manage state constants in a more intuitive way.

Requirements: Write a C program that performs the following tasks.

- Declare an enumeration: enum GradeType {NUMERIC, PASS_FAIL}.

- Declare a union GradeValue that includes: A floating-point field numeric_score (used for

scores from 0.0 to 10.0), and an integer field is_pass (used for pass/fail courses: 1 is

pass, 0 is fail).

- Declare a structure Course that includes course name (string with maximum 20

characters), an enum GradeType variable (named type), and union GradeValue variable

(named result).

- Write a program that prompts the user to input information for a course.

Use a conditional structure to check the value of type, and based on it, allow the user

to input the appropriate field of the union. Then print the corresponding result.

Example:

Input:

Enter course name: Physical Education

Select grading type (1: 10-point scale, 2: Pass/Fail): 2

Enter result (1: Pass, 0: Fail): 1

Output:

--- STUDY RESULT ---

Department of Electronics Page | 4

Computer System and Programming Laboratory (Advanced Program)


Laboratory 4:
DYNAMIC MEMORY ALLOCATION AND LINKED LISTS
Course: Physical Education

Grading type: Pass/Fail

Result: PASS

Check:

1. Print the size of union GradeValue and struct Course. Based on the results, what can be

concluded about the size of a union?

2. For a variable:
union GradeValue u;

u.numeric_score = 8.5;

printf("%d", u.is_pass);

What output do you observe when running the program?

3. Based on Question 2, explain why in practice, when declaring a union, programmers

almost always combine it with an enum variable (such as type in this exercise).

Department of Electronics Page | 5

Computer System and Programming Laboratory (Advanced Program)


Laboratory 4:
DYNAMIC MEMORY ALLOCATION AND LINKED LISTS
EXPERIMENT 3

Objective: Become familiar with dynamic memory allocation on the heap.

Requirements:

- Reuse the Student structure from Experiment 1.

- Write a program that prompts the user to enter an integer n, representing the number

of students.

- Use malloc (or calloc) to dynamically allocate an array of n students.

- Use a loop to input data for all n students and print the list to the screen.

- At the end of the program, make sure to free the allocated memory.

Example:

Input:

Enter number of students: 2

Enter information for student 1:

- Student ID: 2400000

- Full name: Nguyen Van A

- GPA: 4.0

Enter information for student 2:

- Student ID: 2400001

- Full name: Tran Van B

- GPA: 3.9

Output:

--- STUDENT LIST ---

Department of Electronics Page | 6

Computer System and Programming Laboratory (Advanced Program)


Laboratory 4:
DYNAMIC MEMORY ALLOCATION AND LINKED LISTS
1. [2400000] Nguyen Van A - 4.0

2. [2400001] Tran Van B - 3.9

Check:

1. Before starting data input, should you check whether the pointer contain the student

list is NULL? What would happen if the pointer is NULL but no validation or error

handling is performed?

2. When allocating the array of Student using malloc, where is this memory stored?

Why is it mandatory to free the allocated memory before the program terminates?

Department of Electronics Page | 7

Computer System and Programming Laboratory (Advanced Program)


Laboratory 4:
DYNAMIC MEMORY ALLOCATION AND LINKED LISTS
EXPERIMENT 4

Objective:

- Extend dynamically allocated arrays using realloc without losing existing data.

- Understand the concept of memory leaks.

Requirements: Upgrade the program from Experiment 3.

- After the user has entered and displayed a list of n students, add an option to allow

inserting an additional m students into the list.

- If the user enters m > 0, use realloc to resize the student_list array from size n to n + m;

input data for the additional m students and print the complete updated student list.

Example:

Input:

Enter number of additional students: 1

Enter information for student 3:

- Student ID: 2400002

- Full name: Ly Minh C

- GPA: 3.2

Output:

--- STUDENT LIST ---

1. [2400000] Nguyen Van A - 4.0

2. [2400001] Tran Van B - 3.9

3. [2400002] Ly Minh C - 3.2

Department of Electronics Page | 8

Computer System and Programming Laboratory (Advanced Program)


Laboratory 4:
DYNAMIC MEMORY ALLOCATION AND LINKED LISTS
Check:

1. When calling realloc, if the memory block immediately following the current array

does not have enough space to expand by m elements, how does realloc handle this

situation (i.e., memory relocation) to ensure sufficient space while preserving the

original n students?

2. Suppose you allocate memory for an array of 1000 students, and the main() function

terminates without freeing this memory. What happens to that memory region in the

operating system? How can this issue be prevented?

Department of Electronics Page | 9

Computer System and Programming Laboratory (Advanced Program)


Laboratory 4:
DYNAMIC MEMORY ALLOCATION AND LINKED LISTS
EXPERIMENT 5

Objective: Understand the physical structure of a node in a Singly Linked List. Manually

initialize and link nodes to represent a mathematical expression.

Requirements:

- Define a structure Term that includes: float coef and int exp.

- Define a structure Node that includes: a struct Term data, and a pointer to the next node

(struct Node *next).

- Write the function: Node* createNode(float coef, int exp);. This function dynamically

allocates memory (malloc) for a new node, assigns the coefficient and exponent, sets

next = NULL, and returns the address of the created node.

- In the main() function, consider the polynomial: F(x) = 3x² - 4x¹ + 5x⁰. Use createNode

to manually create 3 nodes representing the above terms.

- After that, link them in descending order of exponent. Using only the pointer to the

first node (head), write nested printf statements (using ->next) to display the entire

polynomial.

Example:

Output:

F(x) = 3.0x^2 + -4.0x^1 + 5.0x^0

Check:

1. When the input string contains space, how does the command scanf("%s", ...) behave?

Which function in C is commonly recommended instead for reading strings that

Department of Electronics Page | 10

Computer System and Programming Laboratory (Advanced Program)


Laboratory 4:
DYNAMIC MEMORY ALLOCATION AND LINKED LISTS
contain spaces? Try printing the result again using that function and comment on the

observed behavior.

2. To print the coefficient 5.0 of the last term using only the pointer to the first node

(head), what pointer expression would you use?

3. At the third node (which stores 5x^0), what is the value of the next field?

What is the role of this value in a linked list?

4. If you want to insert a new term of degree 3 (e.g., 8x^3) at the beginning of the

polynomial (making it the new head node), which pointers need to be updated?

Department of Electronics Page | 11

Computer System and Programming Laboratory (Advanced Program)


Laboratory 4:
DYNAMIC MEMORY ALLOCATION AND LINKED LISTS
EXPERIMENT 6

Objective: Apply the pointer-to-pointer (**) technique to modify the head pointer inside

a function.

Requirements:

- Reuse the Node structure and the createNode function from Experiment 5.

Declare the pointer: Node *head = NULL

- Write a function to append a term to the end of the polynomial:

void addTail(Node **head, float coef, int exp)

Note: If the list is empty, the new node becomes the head.

- Write a function to traverse and print the polynomial:

void printPolynomial(Node *head)

This function uses a while loop to traverse the list and prints each term in the format:

(coefficient)x^(exponent). Terms are separated by a "+" symbol.

- Write a function to free the allocated memory:

void freeList(Node **head)

This function traverses the list and frees each node.

- In the main() function: Continuously prompt the user to enter terms (coefficient and

exponent). Stop when the user enters a coefficient of 0. Add each term to the list, print

the final polynomial, and free the allocated memory.

Example:

Input:

Enter polynomial terms (enter coefficient 0 to stop):

Coefficient: 4

Department of Electronics Page | 12

Computer System and Programming Laboratory (Advanced Program)


Laboratory 4:
DYNAMIC MEMORY ALLOCATION AND LINKED LISTS
Exponent: 3

Coefficient: -2.5

Exponent: 1

Coefficient: 7

Exponent: 0

Coefficient: 0

Output:

F(x) = 4.0x^3 + -2.5x^1 + 7.0x^0

Check:

1. In the addTail function, why must the parameter be Node **head instead of Node *head?

What would happen if only Node *head is passed when adding the first node to an

empty list?

2. In the freeList function, why does the following code cause a runtime error?

while (*head != NULL) {


free(*head);
*head = (*head)->next;
}

Rewrite this code using a temporary pointer (Node *temp) to fix the issue.

Department of Electronics Page | 13

Computer System and Programming Laboratory (Advanced Program)

You might also like