summaryrefslogtreecommitdiffstats
path: root/realloc.c
diff options
context:
space:
mode:
Diffstat (limited to 'realloc.c')
-rw-r--r--realloc.c77
1 files changed, 77 insertions, 0 deletions
diff --git a/realloc.c b/realloc.c
new file mode 100644
index 0000000..e9aec19
--- /dev/null
+++ b/realloc.c
@@ -0,0 +1,77 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+typedef struct
+{
+ int length;
+ char *line;
+} sNode;
+
+struct String
+{
+ int index;
+ int size;
+ sNode *arr;
+};
+
+struct String *string_new(char *str);
+void string_append(struct String *a, char *b);
+void string_resize(struct String *s);
+
+struct String *string_new(char *str)
+{
+ struct String *ret = (struct String *) calloc(1, sizeof(struct String));
+ ret->arr = (sNode *) calloc(1, (sizeof(sNode) * 200));
+ ret->size = 200;
+ string_append(ret, str);
+
+ return ret;
+}
+
+void string_append(struct String *a, char *b)
+{
+ if ((a->size-1) == a->index)
+ string_resize(a);
+
+ a->arr[a->index].line = b;
+ a->arr[a->index].length = strlen(b);
+
+ a->index++;
+}
+
+void string_resize(struct String *s)
+{
+ /* quadruple the size */
+ int newSize = s->size * 4;
+ printf("debug: resizing to new size of %d\n", newSize);
+
+ s->size = newSize;
+ sNode *newarr = (sNode *) realloc(s->arr, (sizeof(sNode) * newSize));
+ if (!newarr)
+ {
+ perror("realloc");
+ exit(-1);
+ }
+
+ /* free old array */
+ free(s->arr);
+ s->arr = newarr;
+
+}
+
+int main(int argc, char **argv)
+{
+ if (argc < 2)
+ {
+ fprintf(stderr,"Usage: app n\n");
+ exit(1);
+ }
+
+ struct String *str = string_new("");
+
+ int i;
+ for (i = 0; i < atoi(argv[1]); i++)
+ string_append(str, "anything that can go wrong, will");
+}
+