Re: Returning a struct from a function - strange behavior
- From: Peter Nilsson <airia@xxxxxxxxxxx>
- Date: Tue, 7 Oct 2008 16:28:54 -0700 (PDT)
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
.
- Follow-Ups:
- Re: Returning a struct from a function - strange behavior
- From: CBFalconer
- Re: Returning a struct from a function - strange behavior
- References:
- Returning a struct from a function - strange behavior
- From: DiAvOl
- Re: Returning a struct from a function - strange behavior
- From: CBFalconer
- Returning a struct from a function - strange behavior
- Prev by Date: Re: Demand that Obama release his college records! Where is the media?
- Next by Date: Re: Returning a struct from a function - strange behavior
- Previous by thread: Re: Returning a struct from a function - strange behavior
- Next by thread: Re: Returning a struct from a function - strange behavior
- Index(es):
Relevant Pages
|