Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!rpi!dali.cs.montana.edu!uakari.primate.wisc.edu!samsung!munnari.oz.au!metro!wolfen!hls0!george From: george@hls0.hls.oz (George Turczynski) Newsgroups: comp.lang.c Subject: Re: SIMPLE malloc & pointer question Summary: The error is ... Message-ID: <835@hls0.hls.oz> Date: 7 Aug 90 23:27:43 GMT References: <7206@helios.TAMU.EDU> Lines: 70 Well, for starters, try this code instead: /*** 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 ***/ It produces the output: "scratch: a.out main(): b[2]=5 inita(): a[2]=3 inita(): b[2]=5 main(): a[2]=3 scratch: " Which is probably what you expected of your code ? The reason it failed is because you passed the value of (int *)a to inita(), and not its address. The value was of course NULL, but was then assigned a value by your call to malloc(), and this is perfectly valid. That is why a[2] was meaningful in inita(). The problem is that you altered a stack variable `a' in inita() and not the stack variable `a' in main(), which is what you thought you did. When you got back into main(), `a' was still NULL, and voila, `a[2]' will cause a SIGSEGV to be sent to the process ! I hope you can follow my altered version of your code. There are changes where you see the "/* <<==== */" symbol. The `(*a)' must be used as the `[]' binds tighter than the `*'. If you leave the `()' out you will still get a segmentation violation, but for a different reason. I hope this has answered any questions you had. Have a nice day... George P. J. Turczynski. | ACSnet: george@highland.oz | Phone: 61 48 683490 Computer Systems Engineer. | Fax: 61 48 683474 |---------------------- Highland Logic Pty. Ltd. | I can't speak for the Suite 1, 348-354 Argyle Street | company, I can barely Moss Vale. NSW. 2577 Australia | speak for myself...