Connecting Tech Pros Worldwide Help | Site Map

Problem with strncpy

osfreak's Avatar
Newbie
 
Join Date: Oct 2008
Posts: 17
#1: Jan 21 '09
Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. typedef struct mystruct {
  5.  
  6.     unsigned char uDirFlag;
  7.  
  8.     unsigned int uFileSize;
  9.  
  10.     char uFilename[255];
  11. } teststruct;
  12.  
  13.  
  14. int main()
  15. {
  16.     char *flatbuf;
  17.  
  18.     teststruct *a = (teststruct*)malloc(sizeof(teststruct));
  19.  
  20.     a->uDirFlag = '0';
  21.     a->uFileSize = 55;
  22.  
  23.     strcpy(a->uFilename,"Test message");
  24.  
  25.     int k = sizeof(teststruct);
  26.  
  27.     flatbuf = (char*)malloc(k);
  28.  
  29.     memset(flatbuf,0,k);
  30.  
  31.     strncpy(flatbuf, (char *)a, k);       //strncpy fails to copy uFilename properly
  32.  
  33.     teststruct *b = (teststruct*)flatbuf;      // b has uFilename field all set to 0
  34.  
  35.     return 0;
  36.  
  37. }
  38.  
  39.  
b has its uFilename field set to 0.

Can anyone Pls explain me why the the character values in the struct(uFilename field) were not copied properly??
Needs Regular Fix
 
Join Date: Jul 2008
Posts: 381
#2: Jan 21 '09

re: Problem with strncpy


Becase unsigned int uFileSize has at least two bytes, and all except least significant are zero, and strncpy stops on it.
osfreak's Avatar
Newbie
 
Join Date: Oct 2008
Posts: 17
#3: Jan 21 '09

re: Problem with strncpy


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?
osfreak's Avatar
Newbie
 
Join Date: Oct 2008
Posts: 17
#4: Jan 21 '09

re: Problem with strncpy


I have got it working by using memcpy(),

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

Thanks for your help :)
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#5: Jan 21 '09

re: Problem with strncpy


Quote:

Originally Posted by osfreak View Post

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
osfreak's Avatar
Newbie
 
Join Date: Oct 2008
Posts: 17
#6: Jan 21 '09

re: Problem with strncpy


Got it working... Thanks anyway...
Reply

Tags
string, struct