C
Summary - Debugging
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.
Exercise 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");.
Show example solution
#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;
}
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.
Test yourself
-
Which tool finds memory leaks?
Show answer
valgrind — valgrind checks for memory leaks at run time.
-
Match the debugging tools
- gdb
- Step-by-step tracing
- valgrind
- Memory checking
- printf
- Temporary trace
- -g
- Debug info
Next lesson: Bit masking