SIMPLE malloc & pointer question
George Turczynski
george at hls0.hls.oz
Wed Aug 8 09:27:43 AEST 1990
Well, for starters, try this code instead:
/*** Cut here ***/
#include<stdio.h>
#include<malloc.h>
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 at 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...
More information about the Comp.lang.c
mailing list