malloc-overflow.c revision 17f7bdddd11a2dc5b4be248f756e14b1ebfe207b
1// RUN: %clang_cc1 -triple x86_64-apple-macosx10.7.0 -analyze -analyzer-checker=security.experimental.MallocOverflow -verify %s
2
3typedef __typeof__(sizeof(int)) size_t;
4extern void * malloc(size_t);
5
6void * f1(int n)
7{
8  return malloc(n * sizeof(int));  // expected-warning {{the computation of the size of the memory allocation may overflow}}
9}
10
11void * f2(int n)
12{
13  return malloc(sizeof(int) * n); // // expected-warning {{the computation of the size of the memory allocation may overflow}}
14}
15
16void * f3()
17{
18  return malloc(4 * sizeof(int));  // no-warning
19}
20
21struct s4
22{
23  int n;
24};
25
26void * f4(struct s4 *s)
27{
28  return malloc(s->n * sizeof(int)); // expected-warning {{the computation of the size of the memory allocation may overflow}}
29}
30
31void * f5(struct s4 *s)
32{
33  struct s4 s2 = *s;
34  return malloc(s2.n * sizeof(int)); // expected-warning {{the computation of the size of the memory allocation may overflow}}
35}
36
37void * f6(int n)
38{
39  return malloc((n + 1) * sizeof(int)); // expected-warning {{the computation of the size of the memory allocation may overflow}}
40}
41
42#include <stddef.h>
43extern void * malloc (size_t);
44
45void * f7(int n)
46{
47  if (n > 10)
48    return NULL;
49  return malloc(n * sizeof(int));  // no-warning
50}
51
52void * f8(int n)
53{
54  if (n < 10)
55    return malloc(n * sizeof(int));  // no-warning
56  else
57    return NULL;
58}
59
60void * f9(int n)
61{
62  int * x = malloc(n * sizeof(int));  // expected-warning {{the computation of the size of the memory allocation may overflow}}
63  for (int i = 0; i < n; i++)
64    x[i] = i;
65  return x;
66}
67
68void * f10(int n)
69{
70  int * x = malloc(n * sizeof(int));  // expected-warning {{the computation of the size of the memory allocation may overflow}}
71  int i = 0;
72  while (i < n)
73    x[i++] = 0;
74  return x;
75}
76
77void * f11(int n)
78{
79  int * x = malloc(n * sizeof(int));  // expected-warning {{the computation of the size of the memory allocation may overflow}}
80  int i = 0;
81  do {
82    x[i++] = 0;
83  } while (i < n);
84  return x;
85}
86
87void * f12(int n)
88{
89  n = (n > 10 ? 10 : n);
90  int * x = malloc(n * sizeof(int));  // no-warning
91  for (int i = 0; i < n; i++)
92    x[i] = i;
93  return x;
94}
95
96struct s13
97{
98  int n;
99};
100
101void * f13(struct s13 *s)
102{
103  if (s->n > 10)
104    return NULL;
105  return malloc(s->n * sizeof(int));  // no warning
106}
107
108void * f14(int n)
109{
110  if (n < 0)
111    return NULL;
112  return malloc(n * sizeof(int));  // expected-warning {{the computation of the size of the memory allocation may overflow}}
113}
114
115