From 0cfeedab7e9a46322521039c5e0049f0f81b7f0c Mon Sep 17 00:00:00 2001 From: Merlin Baviere <merlin.baviere@student-cs.fr> Date: Thu, 20 Mar 2025 20:34:22 +0100 Subject: [PATCH] partie 2 realloc --- config/cert_exp_33_realloc.c | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/config/cert_exp_33_realloc.c b/config/cert_exp_33_realloc.c index 7dea465..8cb4bf9 100644 --- a/config/cert_exp_33_realloc.c +++ b/config/cert_exp_33_realloc.c @@ -1,41 +1,43 @@ #include <stdlib.h> #include <stdio.h> +#include <string.h> + enum { OLD_SIZE = 10, NEW_SIZE = 20 }; - -int *resize_array(int *array, size_t count) { - if (0 == count) { + +int *resize_array(int *array, size_t old_count, size_t new_count) { + if (0 == new_count) { return 0; } - - int *ret = (int *)realloc(array, count * sizeof(int)); + + int *ret = (int *)realloc(array, new_count * sizeof(int)); if (!ret) { free(array); return 0; } - + + if (new_count > old_count) { + memset(ret + old_count, 0, (new_count - old_count) * sizeof(int)); + } + return ret; } - + void func(void) { - + int *array = (int *)malloc(OLD_SIZE * sizeof(int)); if (0 == array) { /* Handle error */ - return; } - - /*@ loop unroll OLD_SIZE; */ + for (size_t i = 0; i < OLD_SIZE; ++i) { array[i] = i; } - - array = resize_array(array, NEW_SIZE); + + array = resize_array(array, OLD_SIZE, NEW_SIZE); if (0 == array) { /* Handle error */ - return; } - /*@ loop unroll NEW_SIZE; */ for (size_t i = 0; i < NEW_SIZE; ++i) { printf("%d ", array[i]); } -- GitLab