kittygirl.online

Übung 02 - Fehlerbehandlung, Soriteren

Published at 18.05.2025

Valgrind

Um mit Valgrind das Program während der Laufzeit zu analysieren, muss beim kompilieren das Program mit dem -g flag übersetzt worden sein. So kann Valgrind ausgeführt werden (mit den empfohlenen Flags aus der Übung):

valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes ./lilo

weitere nützliche flags:

  • --track-fds=yes: zeigt alle bei Beendigung des Programms noch offene File Pointer an

Beispiel Programme aus der Präsenzübung

20 Zufällig generierte Integers mit qsort() sortieren

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

#define COUNT 20

static int compare(const void *a, const void *b) {
  // wir wissen, dass pointers zu integers gepasst werden (wir sortieren ints)
  const int *ia = (const int *)a;
  const int *ib = (const int *)b;

  if (*ia < *ib) {
    return -1;
  } else if (*ia == *ib) {
    return 0;
  } else {
    return +1;
  }
}

int main(int argc, char *argv[]) {
  srand(time(NULL));

  // Speicher für die Zahlen anlegen
  int *nums = malloc(sizeof(int) * COUNT);
  if (nums == NULL) {
    perror("malloc");
    exit(EXIT_FAILURE);
  }

  // Zufallszahlen generieren
  for (int i = 0; i < COUNT; i++) {
    int r = rand();
    nums[i] = r;
  }

  qsort(nums, COUNT, sizeof(int), compare);

  // die zahlen sortiert auf stdout ausgeben
  for (int i = 0; i < COUNT; i++) {
    printf("%d\n", nums[i]);
  }

  exit(EXIT_SUCCESS)
}