Monday 15 April 2013

c - Strange results with memcopy -


I am sending a string from one program to another: number lastname firstname middlei ID GPA .

The received program sees the correct string and it is stored in string buffer. The number used in the token and string statement in the string Related case code is shown below.

  tok = strtok (arg, ""); Printf ("First token% s \ n", Tasks); Memcpy (ptr-> student.lname, Token, 10); Tok = strtok (NULL, ""); Mempi (pt-> student.fam, tokay, 10); Tok = strtok (NULL, ""); PTR- & gt; Student.initial = * torque; Tok = strtok (NULL, ""); Sscanf (torque, "% lu", & amp; ptr-> student.SID); Tok = strtok (NULL, ""); Sscanf (Toe, "% F", and PTR-> Students GPA); // Some other indicator and location initial ... printf ("lu% s% s% c% f \ n", ptr-> student. Sid, pt-> student.lumb, pt-> student.fam, PTR-> Student Initial, PTR-> Students GPA);   

The input string is: 5 lastnamereallylong, firstnamereallylong, X, 1234.4.0

which first minimizes the program: 5 The first name of the second name is X 1234 4.0

The output of the second program is as follows:

  first line lastnamere 1234 lastnamereXfirstnamer firstname 4.000000   

Can someone help me to understand what's happening here? I could not properly use the memcopy but I did not think that the sequence of basic information would change.

What's happening here Undefined behavior: You can copy memcpy Which is the first ten characters of tokens, but when tokens are longer than ten characters, this means that the string is not going to be redundant. Passing this string to printf ("% s", ...) with undefined behavior.

To fix this problem, you must either have ptr- & gt; Student.lname [9] = '\ 0' If you want to be with fixed-length strings, or use strdup to allow variable-length strings.

Finally, there is a thread-safe option for using strtok - you can use it.

No comments:

Post a Comment