C:Workshop:2015:D3

De wiki-prog
Révision de 8 janvier 2015 à 14:33 par Slashvar (discuter | contributions)

(diff) ← Version précédente | Voir la version courante (diff) | Version suivante → (diff)
Aller à : navigation, rechercher


The MCQ web site is: http://rendu.infoprepa.epita.fr/intra

Introduction

This session is dedicated to debugging. Your goal is to explore gdb as much as you can.

Since, debugging is an unbound process the subject is open. It may also be a good idea to continue some part that you haven't done yet on the previous sessions.

Produce some code

In order to debug, you need some code. The best solutions is to use code you write, in order to have a good code base, you can use the recycler or the skip list that you have done on the second day.

In order to prepare your code, you must be sure that:

  • no optimization flags are active (use -O0)
  • symbol and debug information are produce by your compiler (option -g)
  • you're working on a freshly compiled code (erase all .o files)

Your goal is to:

  • Use gdb to find your bug
  • Use gdb to examine data structures during code execution
  • Use gdb to explore code execution, function calls …
  • Use gdb to do what ever you want, like modify the memory of a running program …

You can also try to use debug printing to compare the two technics …

Looking for a hidden bug

The purpose of this exercise is to track down a stack overflow bug.

Here is our working code:

# include <stdio.h>
# include <stdlib.h>
 
struct data {
  size_t                a, b, c, d;
};
 
void data_fill(void *p, size_t a, size_t b, size_t c, unsigned d) {
  struct data          *data = p;
  data->a = a;
  data->b = b;
  data->c = c;
  data->d = d;
}
 
void some_code() {
  char          s[] = "My string";
  int           x;
  data_fill(&x, 0xb0b0b0b0, 0xb0b0b0b0, 0xb0b0b0b0, 0xb0b0b0b0 );
  printf("s: %s\n", s);
}
 
int main() {
  some_code();
  return 0;
}
  • compile and run the program, what happened ?
  • use gdb to find the problem

Using valgrind

  • use valgrind to find memory leak in the following code
  • solve the problem
# include <stdlib.h>
# include <stdio.h>
 
struct list {
  int           val;
  struct list  *next;
};
 
struct list* add(struct list *l, int x) {
  struct list          *tmp;
  tmp = malloc(sizeof (struct list));
  tmp->val = x;
  tmp->next = l;
  return tmp;
}
 
int main() {
  struct list          *l = NULL;
  for (int i = 0; i < 100; ++i)
    l = add(l, i);
  for (; l->next != NULL; l = l->next)
    printf("%d -> ", l->val);
  printf("%d\n", l->val);
  return 0;
}