Simvik

Fix: the first job is sometimes wrong

A function frees a list and then reads from it. A medium embedded C problem (Pointers), run and graded in the browser.

medium · Pointers · find-the-bug · use-after-free · heap

Bug report. take_first(list) takes ownership of a job list allocated with malloc, returns its first entry and frees the list. Most of the time the right job comes back, but under load it is sometimes a value no one queued. Fix it by changing at most two lines.

Starter code

int take_first(int *list) {
  free(list);
  return list[0];
}

Example tests

One list

int *jobs = malloc(3 * sizeof(int));
jobs[0] = 7; jobs[1] = 8; jobs[2] = 9;
printf("%d\n", take_first(jobs));

Expected output:

7

Learn it first

  • Pointers · Addresses, arithmetic, const, void pointers and object lifetime.

More Pointers problems