Simplify and fix block allocation
This was just totally broken. Since we used to re-alloc the pes blocks,
we cannot maintain a list of them: the pointers change.
So stop realloc'ing the blocks, and instead just realloc the stitch
list. And simplify the list handling while at it.
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
diff --git a/main.c b/main.c
index 57cddf7..82f0430 100644
--- a/main.c
+++ b/main.c
@@ -32,7 +32,6 @@
.min_y = 65535, .max_y = -65535,
.blocks = NULL,
.last = NULL,
- .listp = &pes.blocks,
};
for (i = 1; i < argc; i++) {
diff --git a/pes.c b/pes.c
index 79e5d90..d0e858c 100644
--- a/pes.c
+++ b/pes.c
@@ -158,16 +158,12 @@
static struct pes_block *new_block(struct pes *pes)
{
- int size = sizeof(struct pes_block) + 64*sizeof(struct stitch);
- struct pes_block *block = malloc(size);
+ struct pes_block *block = calloc(1, sizeof(*block));
if (block) {
- memset(block, 0, size);
- block->max_stitches = 64;
-
+ struct pes_block **pp = pes->last ? &pes->last->next : &pes->blocks;
+ *pp = block;
pes->last = block;
- *pes->listp = block;
- pes->listp = &block->next;
block->color = my_colors[pes->nr_colors++];
}
return block;
@@ -176,6 +172,7 @@
static int add_stitch(struct pes *pes, int x, int y)
{
struct pes_block *block = pes->last;
+ struct stitch *stitch = block->stitch;
int nr_stitches = block->nr_stitches;
if (x < pes->min_x)
@@ -189,14 +186,15 @@
if (block->max_stitches == nr_stitches) {
int new_stitches = (nr_stitches * 3) / 2 + 64;
- int size = sizeof(struct pes_block) + new_stitches*sizeof(struct stitch);
- block = realloc(block, size);
- if (!block)
+ int size = new_stitches*sizeof(struct stitch);
+ stitch = realloc(stitch, size);
+ if (!stitch)
return -1;
block->max_stitches = new_stitches;
+ block->stitch = stitch;
}
- block->stitch[nr_stitches].x = x;
- block->stitch[nr_stitches].y = y;
+ stitch[nr_stitches].x = x;
+ stitch[nr_stitches].y = y;
block->nr_stitches = nr_stitches+1;
return 0;
}
diff --git a/pes.h b/pes.h
index 322cd7e..97578a4 100644
--- a/pes.h
+++ b/pes.h
@@ -19,13 +19,13 @@
struct pes_block *next;
struct color *color;
int nr_stitches, max_stitches;
- struct stitch stitch[];
+ struct stitch *stitch;
};
struct pes {
int nr_colors;
int min_x, max_x, min_y, max_y;
- struct pes_block *blocks, *last, **listp;
+ struct pes_block *blocks, *last;
};
/* Input */