blob: af8600abe5a05c7f5bb7f4129f43c6743b7e6b43 [file] [log] [blame]
Anna Zaksca115102012-05-07 23:30:29 +00001// RUN: %clang_cc1 -analyze -analyzer-checker=unix.MallocSizeof -verify %s
Peter Collingbournedc309672011-12-08 08:31:14 +00002
3#include <stddef.h>
4
5void *malloc(size_t size);
6void *calloc(size_t nmemb, size_t size);
7void *realloc(void *ptr, size_t size);
Ted Kremenek88db6a22012-05-01 00:10:19 +00008void free(void *ptr);
Peter Collingbournedc309672011-12-08 08:31:14 +00009
10struct A {};
11struct B {};
12
13void foo() {
14 int *ip1 = malloc(sizeof(1));
15 int *ip2 = malloc(4 * sizeof(int));
16
Anna Zaksca115102012-05-07 23:30:29 +000017 long *lp1 = malloc(sizeof(short)); // expected-warning {{Result of 'malloc' is converted to a pointer of type 'long', which is incompatible with sizeof operand type 'short'}}
18 long *lp2 = malloc(5 * sizeof(double)); // expected-warning {{Result of 'malloc' is converted to a pointer of type 'long', which is incompatible with sizeof operand type 'double'}}
19 long *lp3 = malloc(5 * sizeof(char) + 2); // expected-warning {{Result of 'malloc' is converted to a pointer of type 'long', which is incompatible with sizeof operand type 'char'}}
Peter Collingbournedc309672011-12-08 08:31:14 +000020
21 struct A *ap1 = calloc(1, sizeof(struct A));
22 struct A *ap2 = calloc(2, sizeof(*ap1));
Anna Zaksca115102012-05-07 23:30:29 +000023 struct A *ap3 = calloc(2, sizeof(ap1)); // expected-warning {{Result of 'calloc' is converted to a pointer of type 'struct A', which is incompatible with sizeof operand type 'struct A *'}}
24 struct A *ap4 = calloc(3, sizeof(struct A*)); // expected-warning {{Result of 'calloc' is converted to a pointer of type 'struct A', which is incompatible with sizeof operand type 'struct A *'}}
25 struct A *ap5 = calloc(4, sizeof(struct B)); // expected-warning {{Result of 'calloc' is converted to a pointer of type 'struct A', which is incompatible with sizeof operand type 'struct B'}}
Peter Collingbournedc309672011-12-08 08:31:14 +000026 struct A *ap6 = realloc(ap5, sizeof(struct A));
Anna Zaksca115102012-05-07 23:30:29 +000027 struct A *ap7 = realloc(ap5, sizeof(struct B)); // expected-warning {{Result of 'realloc' is converted to a pointer of type 'struct A', which is incompatible with sizeof operand type 'struct B'}}
Peter Collingbournedc309672011-12-08 08:31:14 +000028}
Ted Kremenek88db6a22012-05-01 00:10:19 +000029
30// Don't warn when the types differ only by constness.
31void ignore_const() {
32 const char **x = (const char **)malloc(1 * sizeof(char *)); // no-warning
Anna Zaksca115102012-05-07 23:30:29 +000033 const char ***y = (const char ***)malloc(1 * sizeof(char *)); // expected-warning {{Result of 'malloc' is converted to a pointer of type 'const char **', which is incompatible with sizeof operand type 'char *'}}
Ted Kremenek88db6a22012-05-01 00:10:19 +000034 free(x);
35}