0
#include<stdio.h>
int main(){
    int a = 10;
    int *p = &a;
    printf("%d\n", p);
    printf("%d\n", *p);
    printf("%d\n", p + 1);
    printf("%d\n", *(p + 1));
    return 0;
}

In vscode, this code can run normally。

I'm wondering if this is a compiler issue, or if such access is indeed allowed

  • 2
    Reading from `*(p + 1)` is definitely undefined. Code with undefined behavior can appear to run fine, it can crash or it can make monkeys fly out of your nose. – teapot418 Mar 28 '23 at 11:39
  • 2
    All the printfs except for `printf("%d\n", *p);` are undefined behavior. Often in C, undefined behavior looks like your program is "working". – Paul Hankin Mar 28 '23 at 11:39
  • 1
    Yes, you're correct, it's illegal. But if you were expecting to get an explicit error message about this, or for the program to fail in some visible way... welcome to *undefined behavior*. Sometimes, illegal pointer access Just Happen To Work (sort of). – Steve Summit Mar 28 '23 at 11:40
  • @SteveSummit: Saying it is illegal is part of the reason students get confused about this. It is not illegal. The C standard does not forbid a program from trying anything. It only specifies (or leaves unspecified) behaviors of C implementations (including behaviors of programs executing within them). All the phrasing of “shall” or “shall not” in the standard is solely inside the framework of specifying the behaviors of C implementations. If a student thinks something is illegal, they may think it will be stopped. If they think it is undefined, they may understand it is not defined. – Eric Postpischil Mar 28 '23 at 12:23

0 Answers0