Lecture 4: vector_0.c

/* gcc -std=c11 */

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

typedef int T;

struct vector {
	size_t size;
	T *data;
};

struct vector *vector_alloc(size_t n, T initial_val) {
	struct vector *s;

	/* overflow */
	if (n > SIZE_MAX / sizeof(T))
		return NULL;

	s = malloc(sizeof(struct vector));
	/* 1st malloc failed */
	if (!s)
		return NULL;

	s->size = n;
	s->data = malloc(n * sizeof(T));
	/* 2nd malloc failed */
	if (!s->data) {
		/* clean up 1st malloc */
		free(s);
		return NULL;
	}

	for (size_t i = 0; i < n; ++i)
		s->data[i] = initial_val;
	return s;
}

void vector_free(struct vector *s) {
	/* free s->data before s */
	free(s->data);
	free(s);
}

int main(void) {
	size_t i, n = 10;
	struct vector *s = vector_alloc(n, 42);
	for (i = 0; i < n; ++i)
		printf("%zd\n", s->data[i]);
	vector_free(s);
	return 0;
}