Skip to content

Commit e502768

Browse files
authored
[asan] Add test for deferencing zero-sized malloc/calloc (#155933)
ASan fails to catch this, because 0-byte allocations are converted into 1-byte allocations. Bug originally reported by dvyukov
1 parent 7450a00 commit e502768

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// RUN: %clang_asan -Wno-alloc-size -fsanitize-recover=address %s -o %t && %env_asan_opts=halt_on_error=0 %run %t 2>&1 | FileCheck %s
2+
3+
// ASan doesn't catch this because internally it translates 0-byte allocations
4+
// into 1-byte
5+
// XFAIL: *
6+
7+
#include <malloc.h>
8+
#include <stdio.h>
9+
10+
int main(int argc, char **argv) {
11+
{
12+
char *p1 = (char *)calloc(1, 0);
13+
printf("p1 is %p\n", p1);
14+
printf("Content of p1 is: %d\n", *p1);
15+
// CHECK: ERROR: AddressSanitizer: heap-buffer-overflow
16+
// CHECK: {{#0 0x.* in main .*zero_alloc.cpp:}}[[@LINE-2]]
17+
free(p1);
18+
}
19+
20+
{
21+
char *p2 = (char *)calloc(0, 1);
22+
printf("p2 is %p\n", p2);
23+
printf("Content of p2 is: %d\n", *p2);
24+
// CHECK: ERROR: AddressSanitizer: heap-buffer-overflow
25+
// CHECK: {{#0 0x.* in main .*zero_alloc.cpp:}}[[@LINE-2]]
26+
free(p2);
27+
}
28+
29+
{
30+
char *p3 = (char *)malloc(0);
31+
printf("p3 is %p\n", p3);
32+
printf("Content of p2 is: %d\n", *p3);
33+
// CHECK: ERROR: AddressSanitizer: heap-buffer-overflow
34+
// CHECK: {{#0 0x.* in main .*zero_alloc.cpp:}}[[@LINE-2]]
35+
free(p3);
36+
}
37+
38+
return 0;
39+
}

0 commit comments

Comments
 (0)