aboutsummaryrefslogtreecommitdiff
path: root/str_vec.c
blob: 82b61a449c2f69e884ec1a089aa186defb2968b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#define _XOPEN_SOURCE 700
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "str_vec.h"

void str_vec_init(struct str_vec *vec) {
	vec->data = NULL;
	vec->len = 0;
}

void str_vec_push(struct str_vec *vec, const char *new_str) {
	++vec->len;
	vec->data = realloc(vec->data, vec->len * sizeof(char*));
	if (!vec->data) {
		perror("str_vec_push failed to allocate memory for str_vec");
		exit(EXIT_FAILURE);
	}
	vec->data[vec->len - 1] = strdup(new_str);
}

void str_vec_free(struct str_vec *vec) {
	if (vec == NULL) {
		return;
	}
	for (size_t i = 0; i < vec->len; ++i) {
		if (vec->data[i] != NULL) {
			free(vec->data[i]);
		}
	}
	free(vec->data);
	vec->data = NULL;
	vec->len = 0;
}