A quick demonstration of how one can use a debugger to interactively inspect variables in a running program…

The following C program will choose a random number between 1 and 100 and challenge you to guess it.

Let’s cheat and learn just a tiny little bit about debugging with lldb 1 along the way!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
	// Initialize random seed
	srand(time(NULL));

	// Generate a random number between 1 and 100
	int secretNumber = rand() % 100 + 1;
	int guess = 0;

	printf("I have chosen a number between 1 and 100.\n");
	printf("Try to guess it!\n");

	while (guess != secretNumber)
	{
		printf("Enter your guess: ");
		scanf("%d", &guess);

		if (guess < secretNumber) {
			printf("Too low! Try again.\n");
		} else if (guess > secretNumber) {
			printf("Too high! Try again.\n");
		} else {
			printf("Congratulations! You guessed the number!\n");
		}
	}

	return 0;
}

Compile as follows:

$ clang -O0 -g -o guess guess.c
$ ./guess
I have chosen a number between 1 and 100.
Try to guess it!
Enter your guess: 50
Too high! Try again.
Enter your guess: 25
Too low! Try again.
Enter your guess: 

Then attach a debugger to it’s pid

% lldb -p 51114
(lldb) process attach --pid 51114
Process 51114 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGSTOP
    frame #0: 0x00000001834e0c98 libsystem_kernel.dylib`__read_nocancel + 8
libsystem_kernel.dylib`__read_nocancel:
->  0x1834e0c98 <+8>:  b.lo   0x1834e0cb8    ; <+40>
    0x1834e0c9c <+12>: pacibsp 
    0x1834e0ca0 <+16>: stp    x29, x30, [sp, #-0x10]!
    0x1834e0ca4 <+20>: mov    x29, sp
Target 0: (guess) stopped.
Executable binary set to "/Users/denis/guess".
Architecture set to: arm64-apple-macosx-.
(lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGSTOP
  * frame #0: 0x00000001834e0c98 libsystem_kernel.dylib`__read_nocancel + 8
    frame #1: 0x00000001833dc6e4 libsystem_c.dylib`__sread + 24
    frame #2: 0x00000001833b91f8 libsystem_c.dylib`_sread + 32
    frame #3: 0x00000001833b918c libsystem_c.dylib`__srefill1 + 36
    frame #4: 0x00000001833b7024 libsystem_c.dylib`__svfscanf_l + 1580
    frame #5: 0x000000018340e360 libsystem_c.dylib`scanf + 96
    frame #6: 0x00000001003784f0 guess`main at guess.c:20:3
    frame #7: 0x0000000183159d54 dyld`start + 7184
(lldb) f 6
frame #6: 0x00000001003784f0 guess`main at guess.c:20:3
   17  		while (guess != secretNumber)
   18  		{
   19  			printf("Enter your guess: ");
-> 20  			scanf("%d", &guess);
   21  	
   22  			if (guess < secretNumber) {
   23  				printf("Too low! Try again.\n");
(lldb) var -L secretNumber
0x000000016fa87158: (int) secretNumber = 28
(lldb) continue 
Process 51114 resuming
(lldb)  

Back to the shell:

Enter your guess: 28
Congratulations! You guessed the number!

  1. like GDB, except awesome! ↩︎