strncpy behavious different under Linux and Solari

This is a discussion on strncpy behavious different under Linux and Solari within the C Programming forums, part of the General Programming Boards category; Dear all I have the following code which is written in C and compiled under gcc in both Linux and ...

  1. #1
    Unregistered
    Guest

    Question strncpy behavious different under Linux and Solari

    Dear all

    I have the following code which is written in C and compiled
    under gcc in both Linux and Solaris. However, it run differently
    from the two platform.

    In Linux, the gcc is 2.96 and the result is
    Length = 8, value = YYYYMMDD
    Length = 4, value = YYYY
    Length = 4, value = MMDD
    Length = 2, value = MM

    In Solaris, the gcc verison is unknown to me and the result is
    Length = 8, value = YYYYMMDD
    Length = 4, value = YYYY
    Length = 4, value = MMDD
    Length = 4, value = MM

    In Solaris, the code also seems to have memory overrun.

    Can anyone help ?

    #include <string.h>
    #include <stdlib.h>

    main(int argc, char **argv)
    {
    char *strTmp_1;
    char *strTmp_2;
    char *strTmp_3;

    char strTmp[9] = "YYYYMMDD";

    printf("%s%d%s%s\n", "Length = ", strlen(strTmp),
    ", value = ", strTmp);

    strTmp_1 = (char*) malloc(strlen("YYYYY"));
    strTmp_1 = strncpy(strTmp_1, strTmp, strlen("YYYY"));
    printf("%s%d%s%s\n", "Length = ", strlen(strTmp_1),
    ", value = ", strTmp_1);

    strcpy(strTmp, strTmp + strlen("YYYY"));
    printf("%s%d%s%s\n", "Length = ", strlen(strTmp),
    ", value = ", strTmp);

    strTmp_2 = (char*) malloc(strlen("MM") + strlen("\0"));
    strTmp_2 = strcat((char *) memcpy(strTmp_2, strTmp,
    strlen("MM")), "\0");
    printf("%s%d%s%s\n", "Length = ", strlen(strTmp_2),
    ", value = ", strTmp_2);
    }

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >strTmp_1 = strncpy(strTmp_1, strTmp, strlen("YYYY"));
    The strTmp_1 isn't overflowing, it just isn't being NULL terminated. Look at this bit of info from the strncpy help page:
    Code:
    char *strncpy( char *dst,
                   const char *src,
                   size_t n );
    If the string pointed to by src is shorter than n characters, null characters are appended to the copy in the array pointed to by dst, until n characters in all have been written. If the string pointed to by src is longer than n characters, then the result isn't terminated by a null character.
    To null terminate the array, just to this:
    >strTmp_1[4] = '\0';
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21