C Programming

xv6

xv6 Folder Structure

  • mkfs

  • user

  • kernel

Kernel

  • Kernel is the first program that runs when the computer is turned on

  • Everything that happens in that program happens in the kernel space

User

  • Every program that is not in the kernel space

C Fundamentals

Header Files

Standard headers

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

Operating System headers

#include <fcntl.h>
#include <unistd.h>

int main()

This is the main function that OS will run when it runs your program.

int main(int argc, char* arg[]) {
    
}
  • argc refers to

  • arg[] refers to

Types

  • int 32-bit signed integer

  • unsigned int 32-bit unsigned integer

  • short 16-bit signed short

  • unsigned short 16-bit unsigned short

  • long and unsigned long aren't useful in xv6 context

  • In general, you'd want to use uint32_t or similar types for normal programming

  • signed char 8-bit signed char

  • unsigned char 8-bit unsigned char

  • char is neither unsigned nor signed. We don't use it for arithmetic. We will use it for generic blobs of bytes or raw data.

Pointers

Pointer is a variable whose value is the address of another variable

// Two variables
int a = 10;
int b = 20;


// Creating a pointer
int* ptr = &a; 

// Printing the pointer
printf("ptr is equal to %p\n", (void*) ptr); // memory address
printf("*ptr is equal to %d\n", *ptr); // de-referenced value

Arrays

Static arrays don't change size. They act like a pointer in some of use cases.

  • (void*) is put for printf to avoid a compiler warning

// Creating an array
int arr[] = {1, 2, 3, 4, 5}

printf("arr is equal to %p\n", (void*) arr); // some memory address
printf("*arr is equal to %d\n", *arr); // value at 0th index i.e 1 in our case
printf("arr[0] is equal to %p\n", arr[0]); // value at 0th index i.e 1 in our case
ptr = arr;
printf("*(ptr + 1) is equal to %d\n", *(ptr + 1)); // value at 1st index

What is the difference between a pointer and an array? sizeof array is equal to the size of the array in bytes. sizeof pointer is equal to the size of an address, which is 8 bits or 1 byte.

Buffer

Buffer is an informal name for an unstructured collection of bytes

char buf[] = {'a', 'b', 'c', 100, 5, 0, 'f', 'x', 67}

printf("len of buf is: %zu\n", sizeof buf) // 9
printf("len of buf is: %zu\n", strlen(buf)) // 5

Why is sizeof and strlen different? strlen() iterates over the buffer and looks for the value zero. So it terminates when it sees zero. sizeof does not do that.

When you write the 0 byte, you sometimes call it the null byte.

Last updated