Memory Allocation

Son Nguyen snguyen at nprdc.arpa
Wed Feb 8 05:33:15 AEST 1989


In article <7208 at pyr.gatech.EDU>, dvu at 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 <stdio.h>
@ 	
@ 	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.......



More information about the Comp.lang.c mailing list