# C Cheat Sheet This is a collection of important C features. ## Memory Allocation Allocate `size` bytes of memory on the heap: **`void *malloc(size_t size)`** MALLOC MUST BE NULL CHECKED!!! Free previously allocated memory on the heap: **`void free(void *ptr)`** Both are defined in the `stdlib.h` header file. ## String operations Find the length of a string: **`size_t strlen(const char *str)`** returns the length of str. Compare two strings: **`int strcmp(const char *Str1, const char *str2)`** returns 0 if equal Copy a string: **`char *strcpy(char *dest, const char *src)`** returns pointer to destination string dest. All are defined in the `string.h` header file. ## Moving and manipulating memory Move n bytes from src to dest: **`void *memcpy(void *dest, const void *src, size_t n)`** returns pointer to dest. does not work on overlapping src and dest **`void *memmove(void *dest, const void *src, size_t n)`** returns pointer to dest. Does work for overlapping src and dest Fill a block of memory (dest) with a particular value ( c) for n bytes **`void *memset(void *dest, int c, size_t n) //string.h`** returns a pointer to dest ## fork and exec **`pid_t fork() //unistd.h`** returns -1 on error, 0 to the child, and the child pid to the parent. **`void exit(int status) //stdlib.h`** Run another program. The v is for argv and the p is for looking in PATH. **`int execvp(const char *file, char *const argv[]) //unistd.h`** only returns on error with -1. Wait for a child process to end: **`pid_t waitpid(pid_t pid, int *status, int options) //sys/wait.h`** returns the PID of ended process on success. Methods on the status variable: **`WIFEXITED(status)`** returns true if child terminated normally **`WEXITSTATUS(status)`** returns the exit status of the child Wait for any child process to end: **`pid_t wait(int *status) //sys/wait.h`** ## thread management ### Main Methods ``` #include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg) ``` returns 0 on success, error number on error ``` #include <pthread.h> int pthread_join(pthread_t thread, void **retval) ``` returns 0 on success, error number on error ``` #include <pthread.h> void pthread_exit(void *retval) ``` ### Example usage ``` #include <pthread.h> ... void *myfunc(void *arg) { ... pthread_exit(NULL); } ... pthread_t tid; int myarg = 1; pthread_create(&tid, NULL, myfunc, &myarg); ... pthread_join(tid, NULL); ... ``` ## Synchronization ### pthread mutex Example usage: ``` #include <pthread.h> ... pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; ... pthread_mutex_lock(&mutex); // critical section pthread_mutex_unlock(&mutex); ... ``` ## File I/O fopen fclose fgets ## POSIX message queues