pointer allocation

Mark Buda hermit at shockeye.UUCP
Wed Dec 21 05:09:44 AEST 1988


In article <8Xf3eSy00UkZ40cVE0 at andrew.cmu.edu> xj01+ at andrew.cmu.edu (Xue Jue) writes:
>I am try to allocate a list of integer pointers by the following short program.
>But for some reason, after I compiled it and tried to run, it gave me a
>Segmentation fault message. I couldn't see what's wrong there. Could anyone out
>there give me some guide?
>
>
>#include <stdio.h>
>int *(*B);
>
>main()
>{
> *B = (int *) calloc(18,sizeof(int));
>}

Wow, a question I can answer, if not clearly (or correctly) :-)

Problem 1: You are allocating memory for 18 ints, not 18 pointers to ints.
	Try calloc(18,sizeof(int *));
Problem 2: If you were allocating memory for pointers to ints, you would
	want to cast the value returned by calloc to an (int **), not an (int *).
Problem 3: You are storing the pointer returned by calloc() in *B. This is
	very very bad. What you want is to store it in B. Storing it in *B puts
	it in the memory location B points to, and since B is never given a
	value, it doesn't really point anywhere useful. In fact, it is probably
	NULL. And as we all know, dereferencing a NULL pointer can mess up your
	day.

>By the way, this is on IBM RT work station. The same thing has been running on
>IBM PC with microsoft C 5.0.

Shows you something about the IBM PC... :-)
-- 
Mark Buda / Smart UUCP: hermit at shockeye.uucp / Phone(work):(717)299-5189
Dumb UUCP: ...rutgers!bpa!vu-vlsi!devon!shockeye!hermit
I hate this $%$@%!$@%!@$%@#$@!% machine.
"A little suction does wonders." - Gary Collins



More information about the Comp.lang.c mailing list