home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!sun-barr!cs.utexas.edu!asuvax!ennews!envmsa.eas.asu.edu!ptran
- From: ptran@envmsa.eas.asu.edu (Phi-Long Tran)
- Subject: Re: structure question
- Message-ID: <21JUL199200390095@envmsa.eas.asu.edu>
- News-Software: VAX/VMS VNEWS 1.4-b1
- Sender: news@ennews.eas.asu.edu (USENET News System)
- Organization: Arizona State University, Tempe, AZ
- References: <1992Jul21.053858.26677@vuse.vanderbilt.edu>
- Distribution: usa
- Date: Tue, 21 Jul 1992 07:39:00 GMT
- Lines: 68
-
- In article <1992Jul21.053858.26677@vuse.vanderbilt.edu>,
- leegye@vuse.vanderbilt.edu (Gyesung Lee) writes...
-
- >typedef struct a_struct {
- > char *name;
- > int mark;
- > struct a_struct *next;
- >} *A_Type;
-
- >A_Type Global_Root;
-
- ..
-
- >main () /* create a global root and set next ptr to NULL */
- >{
- > Global_Root = (A_Type) malloc (sizeof(A_Type));
- > Global_Root->next = NULL;
- > abc();
- >}
-
- >The right answer should be:
- >
- >In abc: is NULL
- >In abc1: is NULL
-
- >But, the result turns out as follows:
-
- >In abc: is NULL
- >In abc1: not NULL
- >Segmentation fault (core dumped)
-
- >If I modify 'A_Type' structure as follows by switching `mark' and `next',
- >...
- >then, it works correctly.
-
- >I rearranged the elements of `struct a_struct' and ran it.
- >In some case it works, in other cases no luck.
- >Could anyone tell me what is wrong with this program ?
-
- I can see one major problem -- you allocated a pointer, not a whole
- data structure. You declared A_Type as a pointer, so sizeof( A_Type ) is
- the size of a pointer to your type (however many words that may be for your
- machine). Malloc returns you a pointer to an area in the system heap for
- you to store an address, but what you really want is to allocate the whole
- structure. I suggest the following:
-
- struct A_Struct_Tag { ... };
- typedef struct A_Struct A_Type; /* This is what you really want. */
- typedef A_Type *A_Type_Ptr; /* Declare a type for a ptr. to A_Type. */
- ..
- A_Type_Ptr global_A_Ptr;
- ..
-
- The call to malloc would then be:
-
- global_A_Ptr = (A_Type_Ptr) malloc( sizeof( *global_A_Ptr ) );
-
- Originally, when you allocated a pointer with just sizeof( A_Type ),
- you were pointing to an address, not the data structure that you were
- hoping to get. Your random errors reflect de-referencing random locations
- stored in Global_Root. Changing field declaration order does not make that
- much of a difference (usually). I suggest you read a good C book and jump
- to the pointer chapter -- K&R's "The C Programming Language."
-
- ---
- Phi-Long Tran
- ptran@asuvax.eas.asu.edu
- Arizona State University
-