Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ames!ucsd!nprdc!snguyen From: snguyen@nprdc.arpa (Son Nguyen) Newsgroups: comp.lang.c Subject: Memory Allocation Message-ID: <1435@arctic.nprdc.arpa> Date: 7 Feb 89 19:33:15 GMT Sender: news@nprdc.arpa Reply-To: snguyen@nprdc.arpa (Son Nguyen) Distribution: usa Organization: Navy Personnel R&D Center, San Diego Lines: 48 In article <7208@pyr.gatech.EDU>, dvu@pyr.gatech.EDU (Dinh Vu) writes: @ I am learning C, and having difficulty with pointers, and @ structures. The small program below compiled fine, but @ it gave core dump when I run it. Would someone give me @ some light on this matter. @ @ @ #include @ @ struct abc { @ int x; @ int y; @ }; @ @ main() @ { @ struct abc *var; @ @ var->x = 5; @ var->y = 10; @ } @ @ @ @ Dinh Vu Your problem is that you are trying to assign values to the internal fields of structure 'abc' WITHOUT allocating memory for the pointer called 'var'. To fix it, you must put the following statements above the two lines 'var->x = 5' and 'var->y = 10': if ((var = (struct abc *) malloc (sizeof (struct abc))) == NULL) { printf ("ERROR: Can't allocate memory for 'var'\n"); exit (1); } These above statements will solve your problem. Remember that you must ALWAYS allocate memory for the pointers before assigning values for the internal fields of these pointers. Son Nguyen PS: If you have more question about C, ask me.......