Path: utzoo!attcan!uunet!lll-winken!lll-lcc!ames!ncar!gatech!fabscal!mpx1!vu-vlsi!devon!shockeye!hermit From: hermit@shockeye.UUCP (Mark Buda) Newsgroups: comp.lang.c Subject: Re: pointer allocation Message-ID: <275@shockeye.UUCP> Date: 20 Dec 88 19:09:44 GMT References: <8Xf3eSy00UkZ40cVE0@andrew.cmu.edu> Reply-To: hermit@shockeye.UUCP (Mark Buda) Organization: The Lab Rats Lines: 36 In article <8Xf3eSy00UkZ40cVE0@andrew.cmu.edu> xj01+@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 >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@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