Re: Returning a struct from a function - strange behavior



CBFalconer <cbfalco...@xxxxxxxxx> wrote:
DiAvOl wrote:
#include <stdio.h>
typedef struct person {
  char name[40];
  int age;
} Person;

static Person make_person(void);

int main(void) {
  printf("%s\n", make_person().name);
  return 0;
}

static Person make_person(void) {
  static Person p = { "alexander", 18 };
  return p;
}

The above small program when compiled without the
-std=c99 option (using gcc 4.2.3) gives me a warning:
"warning: format ‘%s’ expects type ‘char *’, but
argument 2 has type ‘char[40]’" and also fails with
a segmentation fault when executed.

If I replace the line printf("%s\n", make_person().name);
with printf("%s\n", &make_person().name[0]); everything
works as expected.

Why does this happen? Isn't make_person().name a pointer
to the array's first element?

No.  make_person() returns a struct by value, which has a
field identified by .name.  That field is an array of 40
chars.  It is a portion of the return struct, which has
never been put in accessible memory.

Your alleged 'good' experience with lcc shows a bug in
lcc.

What bug does it show?

--
Peter
.



Relevant Pages