commit 9638d22a9a85472930449602bcb6447313623b3c
parent ebecbb0fa786afd97e91b0faf769886b3fa1a8cc
Author: zerous Naveen Narayanan <zerous@nocebo.space>
Date: Sat, 9 Mar 2019 17:57:14 +0100
realloc throws error invalid next size
Diffstat:
A | sw.c | | | 107 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 107 insertions(+), 0 deletions(-)
diff --git a/sw.c b/sw.c
@@ -0,0 +1,107 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+/* shuffle newline terminated strings */
+
+void shuffle(char *, int);
+
+int
+main(int argc, char **argv)
+{
+ char c, *s, *n, *t;
+ int nword;
+ size_t gf;
+
+ (void) argc;
+ (void) argv;
+
+ gf = 512;
+ s = n = NULL;
+ nword = 0;
+
+ for (;(c = getc(stdin)) != EOF;)
+ {
+ if (n == NULL || n >= (s + (gf - 512))) /* first time */
+ {
+ t = realloc(s, gf);
+ if (t != NULL) {
+ s = t;
+ n = t;
+ *n++ = c;
+ gf += 512;
+ } else {
+ printf("err: realloc\n");
+ return 1;
+ }
+ }
+ else if (c == '\n' || c == ' ') {
+ *n++ = '\0';
+ nword++;
+ }
+ else {
+ *n++ = c;
+ }
+ }
+
+ /* shuffle(s, nword); */
+
+ for (char *t = s; t < n;) {
+ printf("%s\n", t);
+ t += strlen(t) + 1;
+ }
+
+ free(s);
+
+ return 0;
+}
+
+void
+shuffle(char *s, int nword)
+{
+ char w[128];
+
+ for (int i = 0; i < nword ; i++)
+ {
+ int k, q, l, r;
+ char *m, *n;
+
+
+ q = rand()%(nword - 1);
+ l = rand()% (nword - 1);
+ k = 0;
+
+ for (char *t = s; k < nword; k++) {
+ if (k == l)
+ m = t;
+ else if (k == q)
+ n = t;
+ r = strlen(t);
+ t += r + 1;
+ }
+
+ assert(strlen(m) < 128);
+ assert(strlen(n) < 128);
+
+ if (strlen(m) == strlen(n)) {
+ strcpy(w, m);
+ strcpy(m, n);
+ strcpy(n, w);
+ }
+ else {
+ strcpy(w, m);
+ int t = strlen(m) - strlen(n);
+ if (m > n) {
+ memmove((n + strlen(n) + 1 + t), (n + strlen(m) + 1),
+ m - (n + strlen(n) + 1));
+ }
+ else if (m < n) {
+ memmove((m + strlen(m) + 1 - t), (m + strlen(m) + 1),
+ n - (m + strlen(m) + 1));
+ }
+ strcpy(m, n);
+ strcpy(n, w);
+ }
+ }
+}
+