Problem with strncpy

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • osfreak
    New Member
    • Oct 2008
    • 22

    Problem with strncpy

    Code:
    #include<iostream>
    using namespace std;
    
    typedef struct mystruct {
    
        unsigned char uDirFlag;
    
        unsigned int uFileSize;
    
        char uFilename[255];
    } teststruct;
    
    
    int main()
    {
        char *flatbuf;
    
        teststruct *a = (teststruct*)malloc(sizeof(teststruct));
    
        a->uDirFlag = '0';
        a->uFileSize = 55;
    
        strcpy(a->uFilename,"Test message");
    
        int k = sizeof(teststruct);
    
        flatbuf = (char*)malloc(k);
    
        memset(flatbuf,0,k);
    
        strncpy(flatbuf, (char *)a, k);       //strncpy fails to copy uFilename properly
    
        teststruct *b = (teststruct*)flatbuf;      // b has uFilename field all set to 0
    
        return 0;
    
    }
    b has its uFilename field set to 0.

    Can anyone Pls explain me why the the character values in the struct(uFilenam e field) were not copied properly??
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    Becase unsigned int uFileSize has at least two bytes, and all except least significant are zero, and strncpy stops on it.

    Comment

    • osfreak
      New Member
      • Oct 2008
      • 22

      #3
      Is there a way i can force strncpy to copy till the specified bytes?

      or is there any other string copy function to do such an operation?

      Comment

      • osfreak
        New Member
        • Oct 2008
        • 22

        #4
        I have got it working by using memcpy(),

        If there is someother way pls let me know...

        Thanks for your help :)

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #5
          Originally posted by osfreak
          I have got it working by using memcpy(),

          If there is someother way pls let me know...

          Thanks for your help :)
          You aren't copying a string so don't use any str* function. Use memcpy() or memmove() instead.

          kind regards,

          Jos

          Comment

          • osfreak
            New Member
            • Oct 2008
            • 22

            #6
            Got it working... Thanks anyway...

            Comment

            Working...