Bytes behind the values

Memory is just bytes. print shows what they mean; x shows the bytes themselves. Try x/4xb &values[2].

Typed values are interpretations of raw bytes

Level 5 of 13 · interactive GDB exercise · runs in your browser

Start this exercise

What you will learn

Examine the bytes that make up an int, an array and a struct, and explain byte order and padding on this target.

This machine is little-endian (smallest byte first), and the compiler sneaks padding into structs.

The exercise

Use x and the Raw memory tab to look at the bytes of values and p.

You work in a real GDB session on the program below. A breakpoint on line 14 was set and the program was started; all three variables are initialised.

#include <stdio.h>

struct pixel {
    unsigned char r;
    unsigned char g;
    unsigned char b;
    int alpha;
};

int main(void) {
    int values[4] = {1, 2, 0x12345678, -1};
    struct pixel p = {255, 128, 0, 7};
    int *second = &values[1];
    printf("%d %d %d\n", values[0], *second, p.alpha);
    return 0;
}

main.c, compiled with gcc -g -O0 -std=c11 -Wall -fno-omit-frame-pointer -fno-stack-protector -no-pie -fno-pie for 32-bit x86 Linux.

GDB commands you will use

x/<n><fmt><size> <addr>
Examine raw memory, e.g. x/4xw &values (4 hex words), x/8xb &p (8 hex bytes).
print <expr>
Evaluate and show an expression (p total, p &x, p *a, p/x n).
print sizeof(<expr>)
Size of an object or type in bytes.
ptype /o struct pixel
Struct layout with offsets, sizes and holes.
print/x <expr>
Print in hexadecimal. Also /t binary, /c character, /d decimal.
print *<ptr>@<n>
Show n objects in a row starting at a pointer, as an array (p *second@3).
whatis <expr>
Show just the type of an expression.

Common mistakes

Try it in your browser