Quiz C3-2 | CS 2113 Software Engineering - Spring 2021

Quiz C3-2

Submit your answers via this Google Form

Question 1

Pick the right memory diagram for point 1 in the program below:

#include <stdio.h>
#include <stdlib.h>

struct node{
  char * val;
  struct node * next;
};

int main() {
  struct node head;
  char * str = "hey (|:^)";
  head.val = str;
  head.next = malloc(sizeof(struct node));
  head.next->val = str + 4;
}

Question 2

A computer science major who can’t do algebra is trying to modify their grades. The student was able to hack into the administrative code and insert some Evil Code to change their grade.

Did the student introduce a memory leak? If so, how many bytes were leaked, if not, write 0 bytes were leaked.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
  char *name;
  char grade;
} course_t;

int main() {

  course_t *courses[3];

  courses[0] = malloc(sizeof(course_t));
  courses[0]->name = "Basket Weaving";
  courses[0]->grade = 'A';

  courses[1] = malloc(sizeof(course_t));
  courses[1]->name = "Complex Tic Tac Toe Analysis";
  courses[1]->grade = 'A';

  courses[2] = malloc(sizeof(course_t));
  courses[2]->name = "Algebra for CS Majors";
  courses[2]->grade = 'D';

  //... some admin code

  // Begin Evil Code inserted by student
  courses[2] = malloc(sizeof(course_t));
  courses[2]->name = "Algebra for CS Majors";
  courses[2]->grade = 'B';

  // Rest of program
  // ...

  printf("Your grades for the semester are ...\n");
  // prints grades
  free(courses[0]);
  free(courses[1]);
  free(courses[2]);
}

Question 3

Consider the program below, is the print at MARK a memory violation? That is a read of previously free’d memory?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
  char * name;
  short x;
  short y;
} point_t;

int main() {
  point_t * a = malloc(sizeof(point_t));

  char * tmp_name = "Point of Interest";
  a->name = malloc(sizeof(char)*strlen(tmp_name)+1);
  strcpy(a->name, tmp_name); //Copies the string on the right to the left
  a->x = 4;
  a->y = 1;

  point_t b;
  b = *a;
  free(a);

  printf("%s",b.name); //MARK
  free(b.name);
}

Question 4

In the program above, how many bytes are are leaked? (For example, 2048 bytes)

Question 5

Consider the program below, what does it print out? Or does a double free occur
instead? Or a combination of both?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
  char *name;
  short x;
  short y;
} point_t;

int main() {
  point_t *a = malloc(sizeof(point_t));

  char *tmp_name = "Point of Interest";
  a->name = malloc(sizeof(char) * strlen(tmp_name) + 1);
  strcpy(a->name, tmp_name); // Copies the string on the right to the left
  a->x = 4;
  a->y = 1;

  point_t * b;
 
  b = a;
  free(a);

  printf("%s", b->name); //MARK
}

Question 6

How many bytes are leaked by this program?