SIMPLE malloc & pointer question

James C Burley burley at world.std.com
Tue Aug 7 16:59:27 AEST 1990


I think the problem is that you're expecting inita to return the pointer it
allocated for <a>, but that doesn't happen.  main passes to inita the
current values for pointers <a> and <b>.  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 <a>, 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 <a>, 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) <a>, so it can modify
main's copy of <a>.  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 <a>, 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 at world.std.com



More information about the Comp.lang.c mailing list