Skip to content

Commit 705640b

Browse files
authored
Merge pull request #1651 from jeromekelleher/64bit-follow-ups
Follow ups for 64 bit change
2 parents 03a4472 + 05b5f18 commit 705640b

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

c/tests/test_core.c

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/*
22
* MIT License
33
*
4-
* Copyright (c) 2019 Tskit Developers
4+
* Copyright (c) 2019-2021 Tskit Developers
55
*
66
* Permission is hereby granted, free of charge, to any person obtaining a copy
77
* of this software and associated documentation files (the "Software"), to deal
@@ -358,6 +358,19 @@ test_malloc_zero(void)
358358
free(p);
359359
}
360360

361+
static void
362+
test_malloc_overflow(void)
363+
{
364+
#if TSK_MAX_SIZE > SIZE_MAX
365+
tsk_size_t size_max = SIZE_MAX;
366+
void *p = tsk_malloc(size_max + 1);
367+
CU_ASSERT_FATAL(p == NULL);
368+
369+
p = tsk_calloc(size_max + 1, 1);
370+
CU_ASSERT_FATAL(p == NULL);
371+
#endif
372+
}
373+
361374
int
362375
main(int argc, char **argv)
363376
{
@@ -369,6 +382,7 @@ main(int argc, char **argv)
369382
{ "test_blkalloc", test_blkalloc },
370383
{ "test_unknown_time", test_unknown_time },
371384
{ "test_malloc_zero", test_malloc_zero },
385+
{ "test_malloc_overflow", test_malloc_overflow },
372386
{ NULL, NULL },
373387
};
374388

c/tskit/core.c

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -717,9 +717,11 @@ tsk_malloc(tsk_size_t size)
717717
if (size == 0) {
718718
size = 1;
719719
}
720-
/* TODO
721-
* 1. check if size > SIZE_MAX on 32 bit
722-
*/
720+
#if TSK_MAX_SIZE > SIZE_MAX
721+
if (size > SIZE_MAX) {
722+
return NULL;
723+
}
724+
#endif
723725
return malloc((size_t) size);
724726
}
725727

@@ -731,13 +733,23 @@ tsk_realloc(void *ptr, tsk_size_t size)
731733
return realloc(ptr, (size_t) size);
732734
}
733735

736+
/* We keep the size argument here as a size_t because we'd have to
737+
* cast the outputs of sizeof() otherwise, which would lead to
738+
* less readable code. We need to be careful to use calloc within
739+
* the library accordingly, so that size can't overflow on 32 bit.
740+
*/
734741
void *
735742
tsk_calloc(tsk_size_t n, size_t size)
736743
{
737744
/* Avoid calloc(0) as it's not portable */
738745
if (n == 0) {
739746
n = 1;
740747
}
748+
#if TSK_MAX_SIZE > SIZE_MAX
749+
if (n > SIZE_MAX) {
750+
return NULL;
751+
}
752+
#endif
741753
return calloc((size_t) n, size);
742754
}
743755

0 commit comments

Comments
 (0)