patch calloc and add more test

This commit is contained in:
Xamora 2026-09-20 06:19:19 +02:00
parent ddaaeaee6d
commit 2c658cc4ee
3 changed files with 49 additions and 15 deletions

24
main.c
View file

@ -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);
}

2
main.h
View file

@ -7,7 +7,7 @@
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <limit.h>
#include <limits.h>
// DONE
extern size_t ft_strlen(const char *s);

View file

@ -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