1

I have compiled followin gprogram using GCC compiler on Ubuntu platform.

I am wondering why the following program is working fine in C?

Is it undefined behaviour?

#include <stdio.h>

struct str 
{ 
    char arr[0];     
}; 

int main()
{
    struct str s;
    s.arr[0]=1; // I think it is invalid in C
    printf("%d\n", s.arr[0]);
      return 0;
}

Output:

1

and when I print printf("%zu\n", sizeof(s));. it is print 0.

Jayesh
  • 4,755
  • 9
  • 32
  • 62
  • This is supported by gcc extension, IIRC. – Sourav Ghosh Dec 13 '19 at 06:43
  • 2
    It isn't valid C, but an obsolete gcc extension that shouldn't be used. [What happens if I define a 0-size array in C/C++?](https://stackoverflow.com/questions/9722632/what-happens-if-i-define-a-0-size-array-in-c-c/9723093#9723093) – Lundin Dec 13 '19 at 07:44
  • 2
    Even if GCC compiles without warning (did you use `-Wall -Wextra -pedantic`?) the assignment `s.arr[0]=1;` is an out-of-bounds write access. This is undefined behaviour. – the busybee Dec 13 '19 at 07:58

0 Answers0