Question about declaring an array in the stack on runtime

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi folks,

I hope that this is the correct mailing list to ask this question.

I have the following C code snippet:

```c
#include <stdio.h>

int main() {
    unsigned int* arr;
    int some_var = 7;

    if (some_var == 7) {
        arr = (unsigned int[7]){9, 10, 11, 12, 13, 14, 15};
    }

    printf("Value of arr:\n");
    for (unsigned int i = 0; i < 7; i++) {
        printf("%u ", arr[i]);
    }

    return 0;
}
```

I have included the relevant Godbolt link here: https://godbolt.org/z/b4rbn6eGT

I have a few questions related to this code snippet:

1. Is the conditional assignment to `arr` considered undefined
behavior? If it is, which exact clause of the C standard does this
code snippet violate and why? As seen in the Godbolt link, there is
different behavior between GCC and Clang (only GCC `-O1` and above
prints garbage values) which made me suspect that this is UB.

2. Regardless of whether this is UB or not, is it possible for GCC to
also output a warning in `-O0` as in `-O2`? If the behavior changes
across different optimization levels, it seems that it's worth a
warning or two. It can be a different warning instead of
`-Wdangling-pointer` since looking at the produced assembly code, GCC
seems to simply optimize out the whole conditional assignment block in
`-O2`. If it is UB, I understand that it is impossible to catch all
UB, but I am just checking on whether it is possible to catch this
specific one from GCC's perspective. Just FYI, I have also tried using
`-fsanitize=address` and `-fsanitize=undefined` and it seems that
AddressSanitizer would throw a `stack-use-after-scope` error in GCC if
`-fsanitize=address` is specified for both `-O0` and `-O2`, but not in
Clang. `-fsanitize=undefined` does not seem to be able to detect
anything.

If the GCC maintainers consider this an acceptable proposal to add the
warning, I am also willing to post a bug report and develop the
corresponding patch for it, although I would appreciate some guidance
since I am not very familiar with GCC's codebase.

Looking forward to your reply and have a great day ahead!

Best regards,
James Raphael Tiovalen



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux