Debian Codegraph @

gcc/testsuite/c-c++-common/analyzer/ptr-subtraction-1.c

raw
1 #include <stddef.h>
2
3 ptrdiff_t
4 test_invalid_sub_addrs_of_locals (void)
5 {
6 int a; /* { dg-message "underlying object for left-hand side of subtraction created here" } */
7 int b; /* { dg-message "underlying object for right-hand side of subtraction created here" } */
8 return &a - &b; /* { dg-warning "undefined behavior when subtracting pointers \\\[CWE-469\\\] \\\[-Wanalyzer-undefined-behavior-ptrdiff\\\]" } */
9 /* { dg-message "subtraction of pointers has undefined behavior if they do not point into the same array object" "final event" { target *-*-* } .-1 } */
10 }
11
12 ptrdiff_t
13 test_valid_sub_addrs_within_array (void)
14 {
15 int a[10];
16 return &a[7] - &a[3];
17 }
18
19 ptrdiff_t
20 test_invalid_sub_addrs_within_arrays (void)
21 {
22 int a[10]; /* { dg-message "left-hand side" } */
23 int b[10]; /* { dg-message "right-hand side" } */
24 return &a[7] - &b[3]; /* { dg-warning "undefined behavior when subtracting pointers" } */
25 }
26
27
28 ptrdiff_t
29 test_invalid_sub_addrs_between_heap_allocs (size_t n)
30 {
31 char *p = (char *)__builtin_malloc (n); /* { dg-message "left-hand side" } */
32 char *q = (char *)__builtin_malloc (n); /* { dg-message "right-hand side" } */
33 ptrdiff_t d = p - q; /* { dg-warning "undefined behavior when subtracting pointers" } */
34 __builtin_free (p);
35 __builtin_free (q);
36 return d;
37 }
38
39 int arr[42]; /* { dg-message "right-hand side" } */
40 int sentinel; /* { dg-message "left-hand side" } */
41
42 ptrdiff_t
43 test_invalid_calc_of_array_size (void)
44 {
45 return &sentinel - arr; /* { dg-warning "undefined behavior when subtracting pointers" } */
46 }