stupid compilers
William Colburn
schlake at nmt.edu
Sat Sep 1 07:41:33 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);
> }
>
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 <stdio.h>
#include <strings.h>
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
More information about the Comp.lang.c
mailing list