Skip to content

Instantly share code, notes, and snippets.

@willcrichton willcrichton/badvector.c Secret
Last active Feb 5, 2018

Embed
What would you like to do?
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
// There are at least 7 bugs relating to memory on this page.
// Find them all!
// Vec is short for "vector", a common term for a resizable array.
// For simplicity, our vector type can only hold ints.
typedef struct {
int* data; // Pointer to our array on the heap
int length; // How many elements are in our array
int capacity; // How many elements our array can hold
} Vec;
Vec* vec_new() {
Vec vec;
vec.data = NULL;
vec.length = 0;
vec.capacity = 0;
return &vec;
}
void vec_push(Vec* vec, int n) {
if (vec->length == vec->capacity) {
int new_capacity = vec->capacity * 2;
int* new_data = (int*) malloc(new_capacity);
for (int i = 0; i < vec->length; ++i) {
new_data[i] = vec->data[i];
}
vec->data = new_data;
vec->capacity = new_capacity;
}
vec->data[vec->length] = n;
++vec->length;
}
void vec_free(Vec* vec) {
free(vec);
free(vec->data);
}
void main() {
Vec* vec = vec_new();
vec_push(vec, 107);
int* n = &vec->data[0];
vec_push(vec, 110);
printf("%d\n", *n);
free(vec->data);
vec_free(vec);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.