From 2c658cc4ee26361299e3b732ea7ac4173b8c347b Mon Sep 17 00:00:00 2001 From: Xamora Date: Sun, 20 Sep 2026 06:19:19 +0200 Subject: [PATCH] patch calloc and add more test --- main.c | 24 +++++++++++++++++------- main.h | 2 +- src/ft_calloc.s | 38 +++++++++++++++++++++++++++++++------- 3 files changed, 49 insertions(+), 15 deletions(-) diff --git a/main.c b/main.c index 74e5dda..475d624 100644 --- a/main.c +++ b/main.c @@ -179,19 +179,23 @@ test_calloc() { { printf("ft_calloc\n"); - char *error = ft_calloc(2, 10); // return "" - printf("error: %p\n", error); + char *normal = ft_calloc(10, 1); // return "" + printf("normal: %s_%p\n", normal, normal); + for (int i = 0; i <= 10; i++) + printf("'%b' ", normal[i]); + printf("\n"); char *empty = ft_calloc(0, 0); printf("empty: %p\n", empty); - char *overflow = ft_calloc(); + char *overflow = ft_calloc(LONG_MAX, LONG_MAX); + printf("overflow: %s_%p\n", overflow, overflow); char *buf = ft_calloc(10, 1); strcpy(buf, "test"); printf("test: %s_%p\n", buf, buf); - free(error); + free(normal); free(empty); free(buf); } @@ -202,17 +206,23 @@ test_calloc() { { printf("calloc\n"); - char *error = calloc(2, 10); // return "" - printf("error: %p\n", error); + char *normal = ft_calloc(10, 1); + printf("normal: %s_%p\n", normal, normal); + for (int i = 0; i <= 10; i++) + printf("'%b' ", normal[i]); + printf("\n"); char *empty = calloc(0, 0); printf("empty: %p\n", empty); + char *overflow = calloc(LONG_MAX, LONG_MAX); + printf("overflow: %s_%p\n", overflow, overflow); + char *buf = calloc(10, 1); strcpy(buf, "test"); printf("test: %s_%p\n", buf, buf); - free(error); + free(normal); free(empty); free(buf); } diff --git a/main.h b/main.h index 474a49a..03218ac 100644 --- a/main.h +++ b/main.h @@ -7,7 +7,7 @@ #include #include #include -#include +#include // DONE extern size_t ft_strlen(const char *s); diff --git a/src/ft_calloc.s b/src/ft_calloc.s index 7fe6b09..622a81f 100644 --- a/src/ft_calloc.s +++ b/src/ft_calloc.s @@ -6,22 +6,46 @@ section .text global ft_calloc ; rdi = nitems, rsi = size ft_calloc: + ; Check if one of arguments are 0 + cmp rdi, 0 + je malloc_0 + cmp rsi, 0 + je malloc_0 + + ; save rbx push rbx mov rbx, rdi - mul rbx, rsi + ; multiplication and security for overflow xor rdi, rdi + mul rbx, rsi cmovno rdi, rbx; Move if not overflow + cmp rdi, 0 + je end_null + + ; malloc and security if malloc failed call malloc wrt ..plt - cmp rax, 0 - je end + je end_null - mov rdi, rax - mov rsi, rbx - call bzero wrt ..plt + bzero: + dec rbx + mov [rax + rbx], 0 - end: + cmp rbx, 0 + jg bzero + + pop rbx + ret + + end_null: + xor rax, rax pop rbx ret + malloc_0: + mov rdi, 0 + call malloc wrt ..plt + ret + +