| 1 |
/* { dg-skip-if "requires hosted libstdc++ for stdlib malloc" { ! hostedlib } } */ |
| 2 |
|
| 3 |
#include <stdlib.h> |
| 4 |
#include <stdint.h> |
| 5 |
|
| 6 |
/* Tests related to structs. */ |
| 7 |
|
| 8 |
struct base { |
| 9 |
int16_t i; |
| 10 |
}; |
| 11 |
|
| 12 |
struct sub { |
| 13 |
struct base b; |
| 14 |
int16_t j; |
| 15 |
}; |
| 16 |
|
| 17 |
struct var_len { |
| 18 |
int16_t i; |
| 19 |
char arr[]; |
| 20 |
}; |
| 21 |
|
| 22 |
|
| 23 |
void test_1 (void) |
| 24 |
{ |
| 25 |
struct base *ptr = (struct base *) malloc (5 * sizeof (struct base)); |
| 26 |
free (ptr); |
| 27 |
} |
| 28 |
|
| 29 |
void test_2 (void) |
| 30 |
{ |
| 31 |
int32_t *ptr = (int32_t *) malloc (5 * sizeof (struct base)); /* { dg-line malloc2 } */ |
| 32 |
free (ptr); |
| 33 |
|
| 34 |
/* { dg-warning "allocated buffer size is not a multiple of the pointee's size \\\[CWE-131\\\]" "warning" { target *-*-* } malloc2 } */ |
| 35 |
/* { dg-message "\\d+ bytes" "note" { target *-*-* } malloc2 } */ |
| 36 |
/* { dg-message "'int32_t \\*' (\\\{aka '(long )?int \\*'\\\})? here; 'sizeof \\(int32_t (\\\{aka (long )?int\\\})?\\)' is '4'" "note" { target c } malloc2 } */ |
| 37 |
/* { dg-message "'int32_t\\*' (\\\{aka '(long )?int\\*'\\\})? here; 'sizeof \\(int32_t (\\\{aka (long )?int\\\})?\\)' is '4'" "note" { target c++ } malloc2 } */ |
| 38 |
} |
| 39 |
|
| 40 |
void test_3 (void) |
| 41 |
{ |
| 42 |
/* Even though 10 bytes is not a multiple of 4, we do not warn to prevent |
| 43 |
a false positive in case s is the base struct of a struct inheritance. */ |
| 44 |
struct base *ptr = (struct base *) malloc (10); |
| 45 |
free (ptr); |
| 46 |
} |
| 47 |
|
| 48 |
void test_4 (void) |
| 49 |
{ |
| 50 |
struct var_len *ptr = (struct var_len *) malloc (10); |
| 51 |
free (ptr); |
| 52 |
} |
| 53 |
|
| 54 |
void test_5 (void) |
| 55 |
{ |
| 56 |
/* For constant sizes, we warn if the buffer |
| 57 |
is too small to hold a single struct. */ |
| 58 |
struct base *ptr = (struct base *) malloc (1); /* { dg-line malloc5 } */ |
| 59 |
free (ptr); |
| 60 |
|
| 61 |
/* { dg-warning "allocated buffer size is not a multiple of the pointee's size \\\[CWE-131\\\]" "warning" { target *-*-* } malloc5 } */ |
| 62 |
/* { dg-message "allocated 1 byte here" "note" { target *-*-* } malloc5 } */ |
| 63 |
/* { dg-message "'struct base \\*' here; 'sizeof \\(struct base\\)' is '\\d+'" "note" { target c } malloc5 } */ |
| 64 |
/* { dg-message "'base\\*' here; 'sizeof \\(base\\)' is '\\d+'" "note" { target c++ } malloc5 } */ |
| 65 |
} |