Strcpy on SysV vs. BSD.

Greg Hunt hunt at dg-rtp.dg.com
Sat Sep 1 06:27:07 AEST 1990


In article <24351 at adm.BRL.MIL>, hsw at sparta.com (Howard Weiss) writes:
> Here is a short C program that demonstrates the problem:
> 
> main(){
>   char *TTx = "/dev/";
>   char tty[10]; /* works on both SysV and BSD */
> /*  char *tty;	/* works only on BSD */
>   strcpy(tty,TTx);
>   printf("what's in tty now is %s\n",tty);
> }
> 
> When I tried using the above program on SysV with the 'char *tty;'
> declaration, it compiles fine, but core dumps when run.  The same
> thing occurs if I substitute 'while (*tty++ = *TTx++)' in place of the
> library strcpy.  Yet, the 'char *tty' compiles and runs fine on BSD!
> To get this to work on SysV, I used the 'char tty[10]' declaration.
> 
> Howard Weiss
> 

The problem isn't with strcpy, SysV, or BSD, there is an error in the
program.

When you use 'char *tty;', you've built a 'pointer to a char', which
is how you refer to a string in C.  However, the pointer hasn't been
initialized to anything, it doesn't point to any allocated memory.

When you then try the 'strcpy (tty, TTx);', you're trying to copy
information using an uninitialized pointer.  Apparently on the BSD
system you used, the pointer had 'good enough garbage' in it that
it was pointing to valid memory.  In that case, the program
destructively overwrote some part of its address space with the
string.  Ouch!

On the other systems you tried, the pointer had bad garbage in it
(possibly null).  When the program tried to dereference the pointer
it took a validity trap, causing the core dump.  This is the result
I got on my machine when I tried it.

This didn't occur, as you noted, when you used 'char tty [10];',
because tty in that case is a pointer to an array of characters and
the complier initialized the pointer, tty, to point to the allocated
area of memory that it created to hold the 10 elements of the array.

You could also solve the problem by using malloc to allocate an area
of memory and assign the pointer returned by malloc to tty.  It will
then point to valid memory and the strcpy will work.

Some compilers can catch the unintentional use of uninitialized 
variables like this if you use some of their warning switches.  Lint
may also be able to detect things like this (never having used lint,
I don't know, the compiler I use generates nice warnings for
uninitialized variables).

Aren't pointers fun?  I hope my explanation is clear.  Enjoy!

--
Greg Hunt                        Internet: hunt at dg-rtp.dg.com
DG/UX Kernel Development         UUCP:     {world}!mcnc!rti!dg-rtp!hunt
Data General Corporation
Research Triangle Park, NC       These opinions are mine, not DG's.



More information about the Comp.unix.questions mailing list