Lecture 14 Testing with Asserts
main.c
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "ll.h"
int main() {
printf("Testing make_list_from_arr():\n");
// Setup the pre-condition
int arr[] = {3, 7, 4};
int size = 3;
// Run the function
Node *res = make_list_from_arr(arr, size);
// Test the post-condition
assert(res->value == 3);
assert(res->next->value == 7);
assert(res->next->next->value == 4);
}
ll.h
#ifndef LL_H
#define LL_H
typedef struct Node {
int value;
struct Node* next;
} Node;
Node* make_node(int value, Node* next);
// Create a list where each node contains an element of arr
// Pre: arr != NULL, len >= 0
// Post: for each Node *node in the returned list at position i
// node->value == arr[i]
Node* make_list_from_arr(int* arr, int len);
#endif
ll.c
#include <stdlib.h>
#include <stdio.h>
#include "ll.h"
Node* make_node(int value, Node* next) {
Node* node = (Node*)malloc(sizeof(Node));
node->value = value;
node->next = next;
return node;
}
Node* make_list_from_arr(int *arr, int len) {
Node* head;
for (int i = 0; i < len; i++) {
Node* res = make_node(arr[i], head);
// Node *res = make_node(arr[len - 1 -i], head);
head = res;
}
return head;
}
Makefile
CC = gcc
CFLAGS = -g -Wall -std=c11
test_lists: main.o ll.o
$(CC) $(CFLAGS) -o $@ $^
main.o: main.c ll.h
$(CC) $(CFLAGS) -c $<
ll.o: ll.c ll.h
$(CC) $(CFLAGS) -c $<
clean:
rm -f test_lists *.o