stupid compilers

Al Dunbar userAKDU at mts.ucs.UAlberta.CA
Sat Sep 1 09:49:48 AEST 1990


In article <163 at prodix.liu.se>, martin at prodix.liu.se (Martin Wendel) writes:
>
>Can anyone explain to me why this piece of code is OK to run:
>
>           #include <stdio.h>
>           #include <strings.h>
>           main()
>           {
>             char line[];
>             char *tmp = "1234";
>             strcpy(line, tmp);
>             printf("%s\n", line);
>           }
>
>when this produce a segmentation fault:
>
>           #include <stdio.h>
>           #include <strings.h>
>           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"
-------------------+-------------------------------------------



More information about the Comp.lang.c mailing list