Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!zaphod.mps.ohio-state.edu!maverick.ksu.ksu.edu!unmvax!nmt.edu!schlake From: schlake@nmt.edu (William Colburn) Newsgroups: comp.lang.c Subject: Re: stupid compilers Message-ID: <1990Aug31.214133.25530@nmt.edu> Date: 31 Aug 90 21:41:33 GMT References: <163@prodix.liu.se> Organization: New Mexico Institute of Mining and Technology Lines: 50 In article <163@prodix.liu.se> martin@prodix.liu.se (Martin Wendel) writes: > >Can anyone explain to me why this piece of code is OK to run: > > #include > #include > main() > { > char line[]; > char *tmp = "1234"; > strcpy(line, tmp); > printf("%s\n", line); > } > >when this produce a segmentation fault: > > #include > #include > main() > { > char *line; > char *tmp = "1234"; > strcpy(line, tmp); > printf("%s\n", line); > } > It seems to me that they should BOTH fail. You are copying a string to a pointer, and not having the pointer point anyplace. The fact that the first program works is pure luck. #include #include char *malloc(); int strlen(); main() { char *line; char *tmp = "1234"; int strsize; strsize=strlen(tmp); line=malloc(strsize+1); strcpy(line,tmp); printf("%s\n",line); } Schlake