Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!wuarchive!zaphod.mps.ohio-state.edu!van-bc!ubc-cs!alberta!mts.ucs.UAlberta.CA!Al_Dunbar From: userAKDU@mts.ucs.UAlberta.CA (Al Dunbar) Newsgroups: comp.lang.c Subject: Re: stupid compilers Message-ID: <1304@mts.ucs.UAlberta.CA> Date: 31 Aug 90 23:49:48 GMT References: <163@prodix.liu.se> Organization: MTS Univ of Alberta Lines: 38 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); > } > Simple. In the first case, strcpy receives the address of array line, and copies the string to it, clobbering whatever variables happen to follow the array in memory. The program has a bug, but it does not result in an exception. In the second case the address that strcpy tries to use is the value of the pointer line. Since it has not been initialized you should not be surprized that it happens to point somewhere illegal. -------------------+------------------------------------------- Alastair Dunbar | Edmonton: a great place, but... Edmonton, Alberta | before Gretzky trade: "City of Champions" CANADA | after Gretzky trade: "City of Champignons" -------------------+-------------------------------------------