Docsity

COMP 211 Systems Fundamentals Midterm Exam: Dynamic Memory, Memory Diagrams, and Structs, Exams of Computer Science

Partial preview of the text

Download COMP 211 Systems Fundamentals Midterm Exam: Dynamic Memory, Memory Diagrams, and Structs and more Exams Computer Science in PDF only on Docsity!

Midterm 3 - A

COMP 211: Systems Fundamentals

Spring 2025

April 16, 2025

Name:

9-digit PID:

Do not begin until given permission.

Honor Code: I have neither given nor received any unauthorized aid on this assessment.

Signed:

Question 1: Dynamic Memory You are given the skeleton of a C program that reads an unknown

number of student names from standard input, stores them in a resizable array, and prints them all

out at the end. Complete the read_names function on the next page by filling in the missing parts

marked with TODO. The maximum length of a name is defined by MAX_NAME_LEN. You can assume

the user will not enter names longer than this limit.

include < stdio .h >

include < stdlib .h >

include < string .h >

define MAX_NAME_LEN 100

define INITIAL_CAPACITY 2

char ** read_names ( int * num_names ) ;

void free_names ( char ** names , int num_names ) { for ( int i = 0; i < num_names ; i ++) { free ( names [ i ]) ; } free ( names ) ; }

int main () { int num_names = 0; char ** names = read_names (& num_names ) ;

printf ("\ nYou entered % d name ( s ) :\ n " , num_names ) ; for ( int i = 0; i < num_names ; i ++) { printf ("% s \ n " , names [ i ]) ; }

free_names ( names , num_names ) ; return 0; }

Library Function Signatures:

void *malloc(size_t size);

void *realloc(void *ptr, size_t size);

char *strncpy(char *dest, const char *src, size_t n);

Question 2: Memory Diagram.

1 # include < stdio .h > 2 # include < stdlib .h > 3 # include < string .h > 4 5 # define SPACE 100 6 # define SECRET_NUM_1 7 7 # define SECRET_NUM_2 8 8 9 int main () { 10 const char * msg1 = " Hello , World !\ n "; 11 const char * msg2 = " We love Computer Science !"; 12 13 char * str = ( char *) malloc ( SPACE ) ; 14 if ( str == NULL ) { 15 printf (" Memory allocation failed .\ n ") ; 16 return 1; 17 } 18 19 strncpy ( str , msg1 , SPACE ) ; 20 strncpy ( str + SECRET_NUM_1 , msg2 + SECRET_NUM_2 , SPACE / 2) ; 21 str [15] = ’\0 ’; 22 23 printf ("% s \ n " , str ) ; 24 25 free ( str ) ; 26 }

2.1. On the next page, complete the high-level memory diagram for this program just before line

23 is executed. Some of the diagram has already been filled in for you.

  • Assume that the call to malloc succeeds.
  • Be sure to cross out any stack frame that has been deallocated.
  • If a pointer refers to the middle of a block or string, it’s acceptable to draw the arrow point-

ing to the beginning of the block for simplicity.

Additional Information:

  • Function Signatures:

void *malloc(size_t size);

char *strncpy(char *dest, const char *src, size_t n);

  • sizeof(size_t) = 8

2.2. What does the program print?

This page intentionally left blank.