c++ - Is performing arithmetic on a null pointer undefined behavior? -


it looks me following program computes invalid pointer, since null no assignment , comparison equality:

#include <stdlib.h> #include <stdio.h>  int main() {    char *c = null;   c--;    printf("c: %p\n", c);    return 0; } 

however, seems none of warnings or instrumentations in gcc or clang targeted @ undefined behavior in fact ub. arithmetic valid , i'm being pedantic, or deficiency in checking mechanisms should report?

tested:

$ clang-3.3 -weverything -g -o0 -fsanitize=undefined -fsanitize=null -fsanitize=address offsetnull.c -o offsetnull $ ./offsetnull c: 0xffffffffffffffff  $ gcc-4.8 -g -o0 -fsanitize=address offsetnull.c -o offsetnull $ ./offsetnull  c: 0xffffffffffffffff 

it seems pretty documented addresssanitizer used clang , gcc more focused on dereference of bad pointers, that's fair enough. other checks don't catch either :-/

edit: part of reason asked question -fsanitize flags enable dynamic checks of well-definedness in generated code. should have caught?

pointer arithmetic on pointer not pointing array undefined behavior.
also, dereferencing null pointer undefined behavior.

char *c = null; c--; 

is undefined defined behavior because c not point array.

c++11 standard 5.7.5:

when expression has integral type added or subtracted pointer, result has type of pointer operand. if pointer operand points element of array object, , array large enough, result points element offset original element such difference of subscripts of resulting , original array elements equals integral expression. in other words, if expression p points i-th element of array object, expressions (p)+n (equivalently, n+(p)) , (p)-n (where n has value n) point to, respectively, + n-th , − n-th elements of array object, provided exist. moreover, if expression p points last element of array object, expression (p)+1 points 1 past last element of array object, , if expression q points 1 past last element of array object, expression (q)-1 points last element of array object. if both pointer operand , result point elements of same array object, or 1 past last element of array object, evaluation shall not produce overflow; otherwise, behavior undefined.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -