🔥

C Coding Templates

TypeMaster

Malloc Arraylist Example

//Struct type dog
typedef struct dog_t {
     char *name;
     int age;
}dog;
//an arraylist struct to keep track of the list of dogs, and other helpful info
typedef struct arraylist_t {
     dog *list;
     int size;
     int capacity;
}arraylist;

//Malloc 16 elements:
dog *dog_array = (dog *)malloc(sizeof(dog) * 16);

//Assign the list allocated to an isntance of the arraylist struct
arraylist *arr_list = malloc(sizeof(arraylist));
arr_list -> size = 0;
arr_list -> capacity = 16;
arr_list -> list = dog_array;


//Add item back to Arraylist
	//Index into the list at arr_list -> size
	//Initialize the dog struct's data
	//Increase the size of the list

char *static_name = "puppy";
char *dyn_name = malloc(sizeof(char)*(strlen(static_name) + 1));
strcpy(dyn_name, static_name); 
dyn_name[strlen(static_name)] = '\0'; //set null terminator

arr_list -> list[arr_list -> size].age = 1; 
arr_list -> list[arr_list -> size].name = dyn_name; 
arr_list -> size++;


//Realloc when exceeding Array Capacity
//realloc takes in an old pointer and a new size
//copies data from old pointer into new block of memory of reqested size.
int new_size = arr_list -> capacity * 2 *sizeof(dog);
arr_list -> list = realloc(arr_list->list, new_size);

//Freee memory to avoid Memory Leak
free(arr_list -> list[arr_list -> size - 1].name);
arr_list -> size--;

Malloc Error Handing

int *get_array(void) {
    int *ptr = calloc(4, sizeof(int));
    if (!ptr) return NULL;
    ptr[2] = 7;
    return ptr;
}
//always check the result of malloc & friends! If it returns NULL, 
handle it appropriately

Realloc Error Handing

int *get_array(void) {
    int *ptr = malloc(4*sizeof(int));
    if (!ptr) return NULL;
    ptr[2] = 7;
    int *new_ptr = realloc(ptr, 6*sizeof(int));
    if (!new_ptr) { free(ptr); return NULL; }
    ptr = new_ptr;
    ptr[5] = 12;
    return ptr;
} 
//always assign the result of realloc to a new pointer!

Struct Memory Error Handling

struct dinosaur *create_dino(char *name) {
    struct dinosaur *dino = malloc(sizeof(struct dino));
    if (!dino) return NULL;
    dino->name = malloc(strlen(name) + 1);
    if (!dino->name) { free(dino); return NULL; }
    strcpy(dino->name, name);
    dino->coolness = 11;
    return dino;
}
//If you want your struct’s data to be on the heap, you must deep 
//copy any user-provided pointers (including strings) first