SIMPLE malloc & pointer question

Shiping Zhang ping at cubmol.bio.columbia.edu
Wed Aug 8 00:24:53 AEST 1990


In article <7206 at helios.TAMU.EDU> jdm5548 at diamond.tamu.edu (James Darrell McCauley) writes:
>I have the following code:
>---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
>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



More information about the Comp.lang.c mailing list