Skip to content

Commit ebbe7d3

Browse files
committed
optimized zero-filling in calloc
1 parent 1c69db9 commit ebbe7d3

File tree

2 files changed

+24
-10
lines changed

2 files changed

+24
-10
lines changed

src/libc/allocator.src

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,35 @@
44
public _malloc, _free, _realloc
55

66
public _calloc
7+
; void *calloc(size_t nmemb, size_t size)
78
_calloc:
89
pop de
910
pop bc
10-
ex (sp),hl
11+
ex (sp), hl
1112
push bc
1213
push de
1314
call __imulu
1415
push hl
1516
push hl
1617
call _malloc
17-
pop de
18-
add hl,de
19-
xor a,a
20-
sbc hl,de
21-
ld e,a
22-
push de
18+
pop bc ; reset SP
19+
; test for NULL
20+
add hl, bc
21+
xor a, a
22+
sbc hl, bc
23+
pop bc ; BC = size
24+
ret z ; return NULL
25+
; inlined bzero/memset
26+
cpi
27+
add hl, bc
28+
ret c ; size is zero
29+
dec hl
30+
ld (hl), a
31+
ret po ; size is one
2332
push hl
24-
call nz,_memset
25-
pop de
26-
pop de
2733
pop de
34+
dec de
35+
lddr
2836
ret
2937

3038
if defined ALLOCATOR_SIMPLE

test/standalone/asprintf_fprintf/src/main.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,12 @@ int memccpy_tests(void) {
415415
return __LINE__;
416416
}
417417

418+
/* check that no crashes occur with small calloc sizes */
419+
buf = (char*)calloc(1, sizeof(char));
420+
free(buf);
421+
buf = (char*)calloc(0, sizeof(char));
422+
free(buf);
423+
418424
buf = (char*)calloc(file_size + 1, sizeof(char));
419425
if (buf == NULL) {
420426
perror("calloc failure");

0 commit comments

Comments
 (0)