Skip to content

Commit 1791d15

Browse files
Fix double-free bug in stdlib models with --malloc-fail-null
If realloc results in a larger memory block the old one needs to be freed... but this should only happen if the allocation of the new block succeeds. The old model didn't properly check for that, this is now fixed.
1 parent b49f31f commit 1791d15

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#include <stdlib.h>
2+
3+
int main(void)
4+
{
5+
void *ptr = malloc(sizeof(char));
6+
if(ptr == NULL)
7+
return 0;
8+
9+
void *ptr1 = realloc(ptr, 2 * sizeof(char));
10+
if(ptr1 == NULL)
11+
{
12+
free(ptr);
13+
return 0;
14+
}
15+
16+
free(ptr1);
17+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
CORE
2+
test.c
3+
--malloc-may-fail --malloc-fail-null
4+
^\[main.precondition_instance.\d+] line \d+ double free: SUCCESS$
5+
^VERIFICATION SUCCESSFUL$
6+
^EXIT=0$
7+
^SIGNAL=0$
8+
--
9+
--
10+
This is a test checking for a regression where the --malloc-may-fail flag
11+
introduced a double-free bug in the stdlib models with realloc.

src/ansi-c/library/stdlib.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -477,8 +477,10 @@ inline void *realloc(void *ptr, __CPROVER_size_t malloc_size)
477477
void *res;
478478
res=malloc(malloc_size);
479479
if(res != (void *)0)
480+
{
480481
__CPROVER_array_copy(res, ptr);
481-
free(ptr);
482+
free(ptr);
483+
}
482484

483485
return res;
484486
}

0 commit comments

Comments
 (0)