Listing 6. strncpy Program and Results

strncpy function in <glbc-base>/sysdeps/generic/strncpy.c
char *
strncpy (s1, s2, n)
     char *s1;
     const char *s2;
     size_t n;
{
        return strcpy(s1, s2);
}

$cat strcpy.c
#include <stdio.h>
#include <string.h>
int bob(char *aa)
{
        char b[4];

        strncpy(b, aa, sizeof(b));
        return 0;
}

int main()
{
        char *a="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        bob(a);
        return 0;
}

$<compile is same as fig. 3 with strcpy.c instead of hello.c>
$gdb ./str
strcpy     strcpy.c   strcpy2    strcpy2.c
$gdb ./strcpy
<snip for length>
This GDB was configured as "i586-mandrake-linux-gnu"...
(gdb) run
Starting program: /home/dave/code/lj/strcpy
Before main()
Looking for cmdln opt

Program received signal SIGSEGV, Segmentation fault.
0x61616161 in ?? ()
(gdb) print $eip
$1 = (void *) 0x61616161
(gdb)
<And to show strcpy still works>
int bob(char *aa)
{
        char b[50];

        strncpy(b, aa, sizeof(b));
        printf("%s\n", b);
        return 0;
}

int main()
{
        char *a="Thats all folks";
        bob(a);
        return 0;
}
$./strcpy
Before main()
Looking for cmdln opt
Thats all folks
After main()
$

