pastebin - collaborative debugging tool
eckelmann.kpaste.net RSS


gcc does not warn about writes beyond the maximum array index
Posted by Anonymous on Fri 18th Oct 2019 09:59
raw | new post

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #ifndef MY_S_IS_LOCAL
  5. struct my_s
  6. {
  7.         int a[128];
  8.         int b[128];
  9.         int c[128];
  10.         int d[128];
  11. } my_s;
  12. #endif /* MY_S_IS_LOCAL */
  13.  
  14. int main(int ac, char *av[])
  15. {
  16. #ifdef MY_S_IS_LOCAL
  17.         struct my_s
  18.         {
  19.                 int a[128];
  20.                 int b[128];
  21.                 int c[128];
  22.                 int d[128];
  23.         } my_s;
  24. #endif /* MY_S_IS_LOCAL */
  25.  
  26.         /* silence warnings about unused variables*/
  27.         (void)ac;
  28.         (void)av;
  29.         (void)my_s;
  30.  
  31.         for(int i=0; i< 256; i++)
  32.         {
  33.                 my_s.b[i]=0xdeadbeef;
  34.         }
  35.  
  36.         /* prevent optimiser from eliminating |my_s| */
  37.         (void)&my_s;
  38.  
  39.         return EXIT_SUCCESS;
  40. }
  41.  
  42. ##############################################
  43.  
  44. # warnings are generated for global variables...
  45. $ g++ -g -gdwarf-2 -O2 -Wall -Wextra -Waggressive-loop-optimizations x.cpp
  46. x.cpp: In function ‘int main(int, char**)’:
  47. x.cpp:33:23: warning: iteration 128u invokes undefined behavior [-Waggressive-loop-optimizations]
  48.    my_s.b[i]=0xdeadbeef;
  49.                        ^
  50. x.cpp:31:2: note: containing loop
  51.   for(int i=0; i< 256; i++)
  52.   ^
  53.  
  54. # ... but NO warnings are generated for local variables
  55. $ g++ -g -gdwarf-2 -DMY_S_IS_LOCAL -O2 -Wall -Wextra -Waggressive-loop-optimizations x.cpp
  56. $
  57.  
  58. # EOF.

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

To highlight particular lines, prefix each line with {%HIGHLIGHT}





All content is user-submitted.
The administrators of this site (kpaste.net) are not responsible for their content.
Abuse reports should be emailed to us at