-2

In the program

#include<stdio.h>

struct t {
        char a[5];
        char b[];
        } temp;

int main(){
        temp.b[0] = 'c';
        temp.b[1] =  'b';
        temp.b[2] = '\0';
        printf("Size of struct = %lu\n", sizeof(temp));
        printf("String is %s\n", temp.b);

        printf("Address of temp = %p\n", &temp);
        printf("Address of array a = %p\n", &(temp.a));
        printf("Address of b = %p\n", &(temp.b));
}

with output

Size of struct = 5
String is cb
Address of temp = 0x601035
Address of array a = 0x601035
Address of b = 0x60103a

In this program, how exactly is array b being allocated? How long is it? Is this some undefined behavior, which is only succeeding in the dummy program as I am not doing anything else. Running into gdb, I can access some memory locations initialized as zero, which makes me suspect that it is allocating some memory.

I do have an api that requires me to format one element of struct as int a[][SIZE], and I am confused about that.

Also, why is sizeof not taking into account at least something from array b. I am not sure if it is taking it as an array or pointer.

Akshat Harit
  • 814
  • 1
  • 7
  • 13
  • 1
    http://stackoverflow.com/a/11734035/669576 – 001 May 18 '17 at 22:42
  • 1
    `b` is a flexible array member; introduced in C99. – ad absurdum May 18 '17 at 22:44
  • 1
    what you have here is undefined behaviour. The open ended struct stuff people refer to above only works for malloced things. You have a static struct. You are writing off the end of it – pm100 May 18 '17 at 22:45
  • Did you compile this? What does the compiler say? What's not obvious about the behaviour of the compiler? So, why do you ask at all? – too honest for this site May 18 '17 at 23:26
  • @Olaf The compile compiled the program, without any errors or output. I saw the code like this, i.e. with array size as empty in structs, and was curious about memory allocation. The code I had sign had called an assembly call to fill the data struct, so I didn't see that it was allocating memory, hence I asked here. – Akshat Harit May 19 '17 at 17:24

1 Answers1

3

The way you use it is undefined behavior. To answer your immediate question, with static or automatic storage (as you use it), this member has a size of 0. So any index will be invalid. It "seems" to work in your experiment, but remember, doesn't do any bounds checking. In fact, you're doing invalid writes and you're just lucky your example doesn't crash and burn.

Such a member is only allowed as last member of a structure and the reason for this is you can use it with dynamic storage:

struct t *temp = malloc(sizeof(struct t) + 5 * sizeof(char));

will allocate an instance of struct t with temp->b being an array of char of size 5.

  • note, it can also be used with other storage types by making a union with the struct and a char buffer. But dynamic allocation is the most common use. – M.M May 18 '17 at 22:58