CodeBlanks Logo Icon CodeBlanks

Summary - Debugging

  • C course
  • Intermediate
  • Lesson 99/116
  • 5 min

Combine gdb and valgrind to debug a program.

Debugging summary

In this summary you'll combine gdb, breakpoint, watch/print, valgrind and printf debugging into one program. The program does an array operation using dynamic memory and trace output.

The structure: a make_array function allocates an array with malloc and fills it with squares. main takes this array, prints a trace message, computes the sum, frees the memory and prints a final trace. This program can be stepped through in gdb and checked for leaks with valgrind. The trace output lets you see each stage.

Practice Write the summary program

Write int *make_array(int n): allocate with malloc(n * sizeof(int)), fill each element with i * i using for, return the array. In main call int *a = make_array(3);. Print printf("iz: dizi oluşturuldu\n");. Compute the sum with for and print with printf("%d\n", sum);. Free with free(a);. Print printf("iz: bellek serbest bırakıldı\n");.

Starter code

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

// Write make_array: allocate with malloc, fill with squares
// Call make_array(3) in main
// Print "iz: dizi oluşturuldu"
// Compute and print the sum
// Free the memory
// Print "iz: bellek serbest bırakıldı"

int main(void) {
    return 0;
}

Sample solution

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

int *make_array(int n) {
    int *a = malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) {
        a[i] = i * i;
    }
    return a;
}

int main(void) {
    int *a = make_array(3);
    printf("iz: dizi oluşturuldu\n");
    int sum = 0;
    for (int i = 0; i < 3; i++) {
        sum += a[i];
    }
    printf("%d\n", sum);
    free(a);
    printf("iz: bellek serbest bırakıldı\n");
    return 0;
}

Expected output

iz: dizi oluşturuldu
5
iz: bellek serbest bırakıldı

Summary

In this group you learned debugging in depth. You saw gdb basics, breakpoints, watch/print, valgrind and printf debugging. You combined them to write a traced, leak-free program.

Debugging is an inseparable part of software development. gdb for step-by-step tracing, valgrind for memory checks and printf for quick tracing; each has its place. In the next groups you'll move to advanced topics like bitwise operations and typedef. Solid debugging habits are the foundation of confidently writing advanced code.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which tool finds memory leaks?

  • gdb
  • valgrind Correct answer
  • make
  • gcc

Explanation: valgrind checks for memory leaks at run time.

2 Match the debugging tools

Term Meaning
gdb Step-by-step tracing
valgrind Memory checking
printf Temporary trace
-g Debug info

All lessons in Intermediate