Any flag to warn me in GCC if I initialize the structure but skip the element?

Say I have this structure

typedef struct foo {
  int a;
  char b;
  char *c;
} foo;

and I want to create an initialized instance of the structure

foo bar = { .a = 7 .b = 'x' .c = "hello" };

However, if I mess up and forget to initialize one of the elements of the structure that I initialize ... for example ...

foo bar = { .a = 7, .c = "hello" };

... I just forgot to initialize the "b" element --- an error that is easy to detect in the example I gave, but in the case of more complex structures, especially underdeveloped ones, this is definitely plausible.

Is there any flag that I could pass on that would make it generate a warning if I make such a mistake?

+3
source share
2 answers

" " ISO C ( -std=c99), gcc . , gcc, : -Wmissing-field-initializers, , AFAIK, , -Wextra, , :

int main ( void )
{
    foo bar = {123, "foobar"};//failed to init char b member
    foo zar = {123, '\a'};//omitted c initialization 
    return 0;
}

:

warning: initialization makes integer from pointer without a cast [enabled by default]
  foo bar = { 123, "foobar"};
warning: missing initializer for field ‘c’ of ‘foo’ [-Wmissing-field-initializers]
  foo zar = { 123, 'a'};

, , , ... IMO...

, , . , char *, :

foo * init_foo(foo *str, int a, char b, char *c)
{
    if (c == NULL) return NULL;// no char pointer passed
    if (str == NULL) str = malloc(sizeof *str);//function allocates struct, too
    str->a = a;
    str->b = b;
    str->c = calloc(strlen(c) + 1, sizeof *(str->c));//allocate char pointer
    strcpy(str->c, c);
    return str;
}
//optionally include custom free function:
void free_foo ( foo **f)
{
    if ((*f)->c != NULL) free((*f)->c);
    free(*f)
    *f = NULL;//init pointer to NULL
}

... :

foo *new_foo = init_foo( NULL, 123, '\a', "string");//allocate new struct, set all members
//free like so:
free_foo(&new_foo);//pass pointer to pointer
foo stack_foo;
init_foo(&stack_foo, 123, '\a', "string");//initialize given struct
//only free .c member
free(stack_foo.c);
stack_foo.c = NULL;

, , -Wall , --pedantic, ...

+1
  • "-W" gcc.
  • bar.a .a .

, "gcc -W test.c"

test.c:11: warning: missing initializer
test.c:11: warning: (near initialization for âbar.câ)
-1

All Articles