Skip to content

Commit

Permalink
Raise warning for subtraction between void pointers
Browse files Browse the repository at this point in the history
  • Loading branch information
tyfkda committed Feb 25, 2024
1 parent f5a6438 commit 71d0e65
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/cc/frontend/fe_misc.c
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,13 @@ Expr *new_expr_addsub(enum ExprKind kind, const Token *tok, Expr *lhs, Expr *rhs
rtype = array_to_ptr(rtype);
if (!same_type_without_qualifier(ltype, rtype, true))
parse_error(PE_FATAL, tok, "Different pointer diff");
if (is_void_ptr(ltype)) {
// void* - void*
parse_error(PE_WARNING, tok, "Pointer subtraction of void*");
ltype = rtype = ptrof(&tyChar);
lhs = new_expr_cast(ltype, lhs->token, lhs);
rhs = new_expr_cast(rtype, rhs->token, rhs);
}
// ((size_t)lhs - (size_t)rhs) / sizeof(*lhs)
ensure_struct(ltype->pa.ptrof, tok, curscope);
if (is_const(lhs) && is_const(rhs)) {
Expand Down
1 change: 1 addition & 0 deletions tests/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ test_basic() {
compile_error 'variable definition conflict' 'int x = 0; int x = 123; int main(void) {return x;}'
compile_error 'illegal type combination' 'int main(void) {long short x = 99; return x;}'
compile_error 'assign array to struct' 'int main(void) {int a[3][2] = {11,22,33,44,55,66}; struct { int a[3][2]; } s; s = a; return s.a[1][1]; } //-WNOERR'
compile_error 'subtract void pointers' 'int main(void) {char s[16]; void *p = &s[1], *q = &s[15]; return q - p;}'
try_direct 'direct addressing' 99 'int main(int argc, char *argv[]) {if (argc < 0) { *(volatile short*)0x12 = 0x34; return *(volatile int*)0x5678; } return 99;}'
try_direct 'restrict for array in funparam' 83 'int sub(int arr[restrict]) { return arr[0]; } int main(void) { int a[] = {83}; return sub(a); }'

Expand Down

0 comments on commit 71d0e65

Please sign in to comment.