Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!snorkelwacker!bloom-beacon!world!burley From: burley@world.std.com (James C Burley) Newsgroups: comp.lang.c Subject: Re: SIMPLE malloc & pointer question Message-ID: Date: 7 Aug 90 06:59:27 GMT References: <7206@helios.TAMU.EDU> Sender: burley@world.std.com (James C Burley) Organization: The World Lines: 36 In-Reply-To: jdm5548@diamond.tamu.edu's message of 7 Aug 90 02:08:58 GMT I think the problem is that you're expecting inita to return the pointer it allocated for , but that doesn't happen. main passes to inita the current values for pointers and . inita immediately overwrites its own LOCAL COPY (as always in C) with the address of allocated memory, then writes through that address in "a[2]=3;". Then it returns to main. Now, main still has the old (uninitialized) value of , so when it tries to read through that address, anything (including a segment violation) can happen. Even a random number getting output. Meanwhile, the pointer to inita's heap-allocated area has been lost forever, since it was kept only in , which is now popped off the stack (ok, it's probably still there somewhere, but not after the next function call...). Try something like this instead: inita(&a,b); /* Call inita, a is input/output arg, b is input only. */ ... inita(a,b) int *a[]; int b[]; { *a = (int *) malloc... *a[2] = 3; printf(...*a[2]); ... } I might have the precedence wrong -- too zonked to be sure without further playing -- but I hope you get the idea. Here, inita is using indirection through a local copy of a pointer to main's (pointer to) , so it can modify main's copy of . It still does basically the same thing except that after returning, the pointer to the heap-allocated area is still present in main's copy of , and thus your program would work. Unless you need to say "(*a)[2] = 3;" and so on, in which case excuse my sloppiness, please! James Craig Burley, Software Craftsperson burley@world.std.com