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