resize allocation for save function
authorLaurent Mazet <mazet@softndesign.org>
Fri, 23 Aug 2024 16:34:51 +0000 (18:34 +0200)
committerLaurent Mazet <mazet@softndesign.org>
Fri, 23 Aug 2024 16:34:51 +0000 (18:34 +0200)
function.c

index 409b514a39b2b38a62f2f75bf20bede749875109..39174c9ba47b432a40a5f045951393739f552246 100644 (file)
@@ -1,4 +1,3 @@
-#include <assert.h>
 #include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -116,14 +115,16 @@ int _sprintblock (char *buffer, int id, block_t *block)
 char *saveboard (board_t *board, blocks_t *blocks)
 {
     int i;
-    int size = 3 * (8 + 3) + 8 + board->width * board->height + 1;
-    size += 3 * (8 + blocks->nb + 1);
+    int size = 3 * (8 + 2) + 7 + board->width * board->height;
+    size += 3 * (8 + blocks->nb);
     for (i = 0; i < blocks->nb; i++) {
-        size += 3 * (13 + 3) + 14 + blocks->block[i]->width * blocks->block[i]->height + 1;
+        int nbdigits = (i < 10) ? 1 : 2;
+        block_t *block = blocks->block[i];
+        size += 3 * (11 + nbdigits + 2) + 12 + nbdigits + block->width * block->height;
     }
     VERBOSE (INFO, size += board->height * (8 + board->width));
 
-    char *buffer = (char *) calloc (size, 1);
+    char *buffer = (char *) calloc (size + 1, 1);
     CHECKALLOC (buffer);
 
     int l = sprintf (buffer, "width: %d\n", board->width);
@@ -136,7 +137,6 @@ char *saveboard (board_t *board, blocks_t *blocks)
     for (i = 0; i < blocks->nb; i++) {
         l += _sprintblock (buffer + l, i, blocks->block[i]);
     }
-    assert (l <= size);
 
     VERBOSE (INFO, _makecomments (buffer + l, board));