JirR02 99962171df Exercise 12
Added Exercise 12 to Repo
2025-05-23 22:56:38 +02:00
..
2025-05-23 22:56:38 +02:00

Task 1: Operator delete

This task is a text based task. You do not need to write any program/C++ file: the answer should be written in main.md (and might include code fragments if questions ask for them).

Task

All the following code fragments use operator delete and delete[] to deallocate memory, but not appropriately. This can lead to an error (including undefined behaviour) or to a memory leak. Find the mistake in each code fragment, explain whether it results in a memory leak or an error, and in the case of an error, point out the location at which it occurs.

class A {
public:
  A(int sz) {
    ptr = new int[sz];
  }
  ~A() {
    delete ptr;
  }
  /* copy constructor, assigmnent operator, public methods. */
  ...
private:
  int* ptr;
};
struct lnode {
  int value;
  lnode* next;
};

void recursive_delete_linked_list(lnode* n) {
  if (n != nullptr) {
    delete n;
    recursive_delete_linked_list(n->next);
  }
}
class A {
public:
  A() {
    c = new Cell;
    c->subcell = new int(0);
  }
  ~A() {
    delete c;
  }
  /* copy constructor, assignment operator, public methods */
  ...
private:
  struct Cell {
    int* subcell;
  };
  Cell* c;
};
void do_something(int* p) {
  /* Do something */
  ...
}
void f() {
  int v;
  int* w = &v;
  do_something(w);
  delete w;
}
class Vec {
public:
  Vec(int size) {
    array = new int[size];
  }
  ~Vec() {
    delete[] array;
  }
  int& operator[](int idx) {
    return array[idx];
  }
  /* copy constructor, assignment operator, other public methods */
  ...
private:
  int* array;
};

void f() {
  Vec v(5);
  delete[] &v[0];
}

Solution

1. Mistake: The mistake is that `delete` was used instead of `delete[]`

   Nature: "error (undefined behaviour)"

   Error location (if applicable): The mistake happens when the deconstructor `~A()` is called.

2. Mistake: The mistake is that the `lnode` is first deleted and then an attribute of the `lnode` is used, which was already deleted

   Nature: "error" and memory leak"

   Error location (if applicable): The mistake happens in the `if` function when `n` is deleted and recursively recalled.

3. Mistake: The mistake is that we only delete `c`without deleting the pointer pointing to the `subcell`.

   Nature: "memory leak"

   Error location (if applicable): The mistake happens when `c` is deleted.

4. Mistake: The mistake is that we try to delete an integer from the stack memory.

   Nature: "error (undefined behaviour)"

   Error location (if applicable): The mistake happens when `w` is deleted

5. Mistake: The mistake is that `delete` tries to delete the address and not the value allocated tot he memory.

   Nature: "error (undefined behaviour)"

   Error location (if applicable): The mistake happens when `&v[0]` is deleted.