Path: utzoo!attcan!uunet!cs.utexas.edu!rutgers!cunixf.cc.columbia.edu!cubmol!ping From: ping@cubmol.bio.columbia.edu (Shiping Zhang) Newsgroups: comp.lang.c Subject: Re: SIMPLE malloc & pointer question Message-ID: <1990Aug7.142453.6895@cubmol.bio.columbia.edu> Date: 7 Aug 90 14:24:53 GMT References: <7206@helios.TAMU.EDU> Reply-To: ping@cubmol.bio.columbia.edu (Shiping Zhang) Organization: Dept. of Biology, Columbia Univ., New York, NY Lines: 44 In article <7206@helios.TAMU.EDU> jdm5548@diamond.tamu.edu (James Darrell McCauley) writes: >I have the following code: >---cut here >#include >#include >main() >{ > int *a,*b; > > b=(int *)malloc( (unsigned) 4*sizeof(int)); > b[2]=5; > printf("main(): b[2]=%d\n",b[2]); > inita(a,b); > printf("main(): a[2]=%d\n",a[2]); >} > >inita (a,b) >int a[],b[]; >{ > a=(int *)malloc( (unsigned) 4*sizeof(int)); > a[2]=3; > printf("inita(): a[2]=%d\n",a[2]); > printf("inita(): b[2]=%d\n",b[2]); >} >---cut here >which produces the following output: > >main(): b[2]=5 >inita(): a[2]=3 >inita(): b[2]=5 >Segmentation fault (core dumped) > Remember that in C, function arguments are passed by value and their original values are not changed no matter what operation has been applied to them in the called functions. So in inita(), a is assigned a value (the address of some memery location), but the value is not saved when return from that function and a points to nowhere or anywhere. The simplest way to solve this problem in this case is just to move the first statement of inita() to somewhere in the main function before inita is called. -ping