Lecture Notes

Learning assistant supported notes for CS 35L


Project maintained by UCLA-CS-35L Hosted on GitHub Pages — Theme by mattgraham

C

Basics

An example C program may look like

#include <stdio.h>

int main(){
    printf("Hello World");
    return 0;
}

You should remember for CS31 what each line does, but for a quick recap

C has primitive data types

There are other data types that you may run into like unsigned, size_t, and int32_t for example depending on what header files you use.

Then, we also have arrays, strings, and structs.

#include <string.h>

int main(){
    int a[2] = {1,2};
    char a[] = "yo what up";

    struct yo{
        int a;
        char b;
    } typedef yuh;
}

Important things to note are

Pointers

A program using pointers might look like

int main(){
    int a=0;
    int *b = &a;
    int c = *p;
    *p = 1;
}

A pointer associates a memory location with a data value. So, in this program, we

So, at the end of the day, we might have values like a=1, b=0x777777ff,c=0. Note how a and c are not the same!

This ties into dynamic memory. Often, we don’t know how big we want containers to be. We can thus allocate / free memory on the heap to get around that issue. Note,

Compiling

Most people use gcc to compile C code. An example command could be gcc -o output input.c

which compiles the input.c file to an executable called output which can normally be run through ./output.

Some common options include

When compiling, there are a few intermediary steps. Notably,

Makefile

We use makefiles to provide an a way to easily build executables that may require a lot of different commands / flags / etc. to create. So, you can simply run make in your terminal to create your executable!

An example makefile may look like

CC = gcc

default: exampleOut

exampleOut: example.o
    $(CC) -o $@ example.o

clean:
    rm -f example.o exampleOut

The format of each command is target: dependency sysCommand(s)

So, the above commands allow the user to, on the command line, run

make exampleOut # create the executable; make would also work
make clean # remove the executable

Some other aspects of makefile include

Debugging

GDB and Valgrind are two tools that you can use to debug your code(aside from print statements🫨)

GDB

To use gdb, compile your code with the -g flag. Then, run gdb <filename>.out GDB is mostly used for stepping through code line by line and checking variables values.

Common commands you can run are

Valgrind

To use valgrind, compile your code with the-g flag. Then, run valgrind --leak-check=full ./<filename>.exe Valgrind is mostly used for looking at memory management issues!


Aside. Assignment 6 may or may not be less focused on C/GDB/Makefiles in Spring 2025 compared to previous quarters. However, it should still show up on your final in an equal amount!