CS 449 – Midterm 2 Practice Problems

Answers in red

1.) For the program below, what will the stack look like if execution is paused at the line marked HERE? (You may ignore padding and alignment.)

 

 

int g(char *a) {

    //HERE

    return strlen(a);

}

 

 

int main()

{

    int x;

    x = g("hello");

    return 0;

}

 

 

Stack grows down

 

Main's EBP

 

Return address to main

 

Pointer to "hello"

 

x

 

Old EBP

 

 

2.) Answer the following about a memory region of 20 MB that has a chunk size of 1MB that is managed with a linked list using best fit allocation.

a.) Assume the region is initially empty. Show the list after allocations of size 4, 6, 3, and 2 (in that order).

 

 

 


b.) From the list in part (a), free the 6 and 3 MB chunks. What is the resulting linked list?

 

 

 


1

Free

 

4

Used

 

2

Used

 

9

Free

 

4

Used

 
c.) Finally, a request for a chunk of size 4 occurs. Show the linked list from part (b) with the new allocation.

 

 

 

3.) Assume the following structure definition:

struct person {

    int age;

    char name[100];

};

 

a.)    Write a function called compare_person that you could pass to qsort as a comparator, which arranges the people by decreasing age, with ties sorted in alphabetical order.

 

int compare_person(const void *a, const void *b) {

    struct person *p1 = a;

    struct person *p2 = b;

 

    if(p1->age > p2->age) {

        return -1;

    }

    else if(p1->age < p2->age) {

        return 1;

    }

    else {

        return strcmp(p1->name, p2->name);

    }

}

 

 

b.)    Write the call to qsort that would sort the array: struct person people[20];

 

qsort(people, 20, sizeof(people[0]), compare_person);

 

4.) Write a macro that finds the minimum of its three arguments.

There are several ways to do this:

#define MIN(a, b, c) ((a) < (b))? (((a) < (c)) ? (a) : (c)) : (((b) < (c)) ? (b) : (c))

 

or

 

#define MIN2(a, b) (((a) < (b)) ? (a) : (b))

#define MIN(a, b, c) MIN2(MIN2(a, b), MIN2(b, c))

 

Etc.