Skip to content
Visual explainer 4h to learn 4 steps

Structs, strings & bit manipulation

Model data with structs and handle C strings and bit flags safely.

By Invicly Tech, , in Linux System Programming. About 10 minutes to read.

Topic 2 of 42

In short

Structs group related fields, and Linux APIs use them everywhere, from struct stat to struct sockaddr_in. C strings are just char arrays ending in a zero byte, so length and buffer size must be tracked by hand. Bit flags packed into integers are how system calls accept options like O_CREAT | O_TRUNC.

Explained simply

A struct is a labelled box that groups related values. A person might have a name, an age and an ID; a struct keeps them together so you can pass them around as one thing. Linux uses structs everywhere: struct stat describes a file, struct timespec holds a time.

A C string is not a special type. It is just an array of chars that ends with a zero byte, written as \0 and called the NUL terminator. Every string function walks the bytes until it finds that zero. If the zero is missing, the function keeps walking into memory it should not touch.

Bit flags pack many yes/no options into one number. Each option owns one bit. You switch options on with | (OR) and test them with & (AND). That is why you write open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644).

These three tools are simple, but small slips cause real security bugs. Learning the safe habits early, like always passing a buffer size, saves a lot of pain.

Press Play on a diagram to walk through it one step at a time.

CompareWays to shape data in C
struct
  • Fields laid out in declaration order
  • Size includes alignment padding
  • Access with . or ->
  • Used by stat, sockaddr, timespec
union
  • All members share the same memory
  • Size of the largest member
  • Only one member valid at a time
  • Used in epoll_data and sigval
Bit flags
  • Options packed into one integer
  • Combine with |
  • Test with &
  • Used by open flags and mode bits
LayersBytes of struct { char c; int n; char d; } on x86-64
  1. 1
    Offset 0: c

    1 byte of data

  2. 2
    Offsets 1-3: padding

    So n starts on a 4-byte boundary

  3. 3
    Offsets 4-7: n

    4-byte int

  4. 4
    Offset 8: d

    1 byte of data

  5. 5
    Offsets 9-11: tail padding

    Total 12, so arrays stay aligned

In depth

Why sizeof(struct) is often bigger than you expect

CPUs read memory fastest when a value starts at an address that is a multiple of its size. An int likes to start on a 4-byte boundary, a pointer or double on an 8-byte boundary. To make that happen, the compiler inserts unused padding bytes between fields and at the end.

So struct { char c; int n; char d; } is usually 12 bytes, not 6: 1 byte for c, 3 padding, 4 for n, 1 for d, 3 padding. Reordering fields from largest to smallest, as in { int n; char c; char d; }, shrinks it to 8 bytes. This matters when you store millions of structs, and it is why you must never write a struct straight to a file or socket and expect another machine to read it the same way.

  • Order fields largest to smallest to cut padding
  • Use offsetof(type, field) to see where a field sits
  • Do not send raw structs over the network

Safe string habits

Most string bugs come from copying into a buffer that is too small. strcpy and strcat never check the size, so they can write past the end. strncpy looks safer but does not add a NUL if the source is too long, which creates a new bug.

The simplest safe tool is snprintf(dst, sizeof dst, "%s", src). It never writes more than the size you give, always adds the NUL, and returns how long the full result would have been. If that return value is greater than or equal to the size, the text was cut short and you can react.

Also remember that strlen does not count the NUL. A string of length 5 needs 6 bytes.

  • Prefer snprintf over strcpy, strcat and sprintf
  • Check snprintf's return for truncation
  • Buffer size = strlen + 1
CompareCopying a string into a buffer
strcpy, strcat
  • No size check at all
  • Can write past the end
  • Avoid
strncpy
  • Takes a size limit
  • No NUL if the source is too long
  • Easy to misuse
snprintf
  • Never writes more than the size
  • Always adds the NUL
  • Return value shows truncation

Working with bits

Define each flag as a different power of two, usually with a shift: (1u << 0), (1u << 1), (1u << 2). Use unsigned types so shifts behave predictably.

The four everyday operations are: set a flag with flags |= F; clear it with flags &= ~F; flip it with flags ^= F; and test it with (flags & F) != 0. The kernel uses exactly this pattern. File mode bits like 0644 are three groups of read, write and execute bits written in octal, which is why each digit runs from 0 to 7.

  • Set: flags |= F
  • Clear: flags &= ~F
  • Toggle: flags ^= F
  • Test: if (flags & F)
FlowOne flags variable, step by step
  1. 1
    Start

    flags = 0b000

  2. 2
    Set READ (1u << 0)

    flags |= READ: 0b001

  3. 3
    Set EXEC (1u << 2)

    flags |= EXEC: 0b101

  4. 4
    Clear READ

    flags &= ~READ: 0b100

  5. 5
    Test EXEC

    (flags & EXEC) != 0 is true

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Define structs and use typedef~1h
  2. 2
    Handle null-terminated strings safely~1h
  3. 3
    Use bitwise operators for flags~1h
  4. 4
    Understand padding and alignment~1h

Key points

  • p->field is shorthand for (*p).field.
  • A C string needs one extra byte for the terminating NUL.
  • Prefer snprintf and explicit lengths over strcpy and strcat.
  • The compiler inserts padding so fields stay aligned; sizeof shows the real size.

Key terms

Tap a card to flip it. 0/5 known

Examples

c
#include <stdio.h>

#define F_READ  (1u << 0)
#define F_WRITE (1u << 1)

struct user { char name[16]; unsigned flags; };

int main(void) {
  struct user u = { .flags = F_READ | F_WRITE };
  snprintf(u.name, sizeof u.name, "%s", "alice");
  if (u.flags & F_WRITE) printf("%s can write\n", u.name);
  printf("sizeof(struct user) = %zu\n", sizeof u);
  return 0;
}

Bit flags, a struct and bounded string formatting.

Seeing padding with sizeof and offsetof

We define the same three fields in two orders and print their sizes. The first layout wastes 6 bytes on padding. The second groups the small chars together after the int, so only 2 bytes of tail padding remain. offsetof shows exactly where each field lands. Run it and compare the numbers with the diagram.

c
#include <stddef.h>
#include <stdio.h>

struct bad  { char c; int n; char d; };
struct good { int n; char c; char d; };

int main(void) {
  printf("bad:  %zu bytes, n at %zu\n", sizeof(struct bad), offsetof(struct bad, n));
  printf("good: %zu bytes, c at %zu\n", sizeof(struct good), offsetof(struct good, c));
  return 0; /* bad: 12, n at 4; good: 8, c at 4 */
}

Building a path without overflowing

A program joins a directory and a file name into one path. With strcpy and strcat a long name would overflow the buffer. snprintf writes at most sizeof path bytes and returns the length it wanted. If that is too big, we report the error instead of using a cut-off path, which could point at the wrong file.

c
#include <stdio.h>

int main(int argc, char **argv) {
  const char *dir = "/var/log";
  const char *name = argc > 1 ? argv[1] : "syslog";
  char path[32];
  int n = snprintf(path, sizeof path, "%s/%s", dir, name);
  if (n < 0 || (size_t)n >= sizeof path) {
    fprintf(stderr, "path too long\n");
    return 1;
  }
  printf("%s\n", path);
  return 0;
}

Quick reference

  • p->x is the same as (*p).x
  • A string of length n needs n + 1 bytes
  • snprintf(buf, sizeof buf, ...) is the safe default for building strings
  • strncpy may leave the result without a NUL terminator
  • Flags: set |=, clear &= ~, test &
  • Use 1u << k for bit k so shifts stay unsigned
  • offsetof(struct t, f) prints a field's byte offset
  • sizeof on an array gives bytes; on a pointer it gives 8 on x86-64

Common mistakes

  • strncpy does not always NUL-terminate the destination.
  • Assuming the size of a struct equals the sum of its fields.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does flags &= ~F_WRITE do?

Question 2

2char buf[8]; snprintf(buf, sizeof buf, "%s", "abcdefghij"); what does buf hold?

Question 3

3Why might sizeof(struct s) be larger than the sum of its fields?

Question 4

4Inside a function taking char *s, what is sizeof s on 64-bit Linux?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a function that counts how many times a character appears in a C string, without using strlen.

  2. Exercise 2medium

    Define permission flags P_READ, P_WRITE, P_EXEC and write a function that turns a flags value into a string like "rw-".

  3. Exercise 3hard

    Reorder struct rec { char tag; double value; char flag; int id; short kind; } to use the least memory on x86-64. State the old and new sizes and check them with sizeof.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between char s[] = "hi" and char *s = "hi"?
The first makes a writable array of 3 bytes on the stack. The second points at a string literal stored in read-only memory, and writing to it crashes or is undefined behaviour.
Is strlcpy available on Linux?
glibc added strlcpy and strlcat in version 2.38, but older systems lack them. snprintf works everywhere and gives the same safety.
When should I use typedef with structs?
It is a style choice. typedef struct point point; saves typing, while the Linux kernel style prefers writing struct point everywhere so it is obvious the type is a struct.

Go deeper

ShareXLinkedInWhatsApp