LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

The problem of function "CopyBytes"

I encounted a very strange problem when using the function of "CopyBytes", shown as below
....
 
CopyBytes (Pattern1, 0, LineBuffer, (PatternPosition1+16), i);
printf("%d, %s\n",i,Pattern1);
.....
 
 
The printf function will output :
13, MainsequenceA
4, XsssButtonpBOYAAAC 
 
The output of line 2 is very strange, since we have defined output size to 4, why it could be a string of "XsssButtonpBOYAAAC "??
 
I also attached my source codes, the function of CopyBytes is in Line109.
 
Thanks
Jacky
0 Kudos
Message 1 of 4
(3,418 Views)

Although you have copied the 4 bytes you wanted, you did not terminate the string. So the printf() function will just continue reading from the string address you give it until it finds a 0 and then it will stop. An alternative function you might find useful is strncpy(), which will do a similar job to CopyBytes() but will automatically add the terminating 0 character after the copy operation.

JR

0 Kudos
Message 2 of 4
(3,412 Views)
strncpy will not add a terminating NULL in this case.  From the help for strncpy:

This function copies not more than a specified amount of characters (characters following an ASCII NUL byte are not copied) from a source string to a target string.  If copying takes place between two objects that overlap, the behavior is undefined. 

If an ASCII NUL byte is found in the source buffer within the specified number of bytes, NUL bytes are written to the target until the specified number of characters have been filled in.

If no ASCII NUL byte is found within the specified number of bytes, the function returns after copying the specified number of bytes and does NOT append an ASCII NUL byte to the buffer.

If you want to guarantee that an ASCII NUL byte is at the end of the copied bytes, you can use the following:

    strncpy (target, source, n);
    target[n] = 0;

/*-------------------- Prototype ---------------------*/
char *strncpy (char Target_String[],
               const char Source_String[], size_t Max_Chars);

Jacky has specified that 4 bytes should be copied from the source to the target.  The terminating NULL was at the 5th byte.  According to the help, strncpy will copy no more than 4 bytes to the target string.

This is also a duplicate post.  I've posted an alternative solution.




----
I am the founder of CnCSoftwareSolutions. When not cleaning up baby drool, I write about test data or work on Vision, a tool for understanding your test data. Visit me at www.cncsoftwaresolutions.com
0 Kudos
Message 3 of 4
(3,398 Views)

I stand corrected! (Thought it would be a mistake to rely on my memory) Smiley Very Happy

JR

0 Kudos
Message 4 of 4
(3,386 Views)