For example
sprintf(pos,"%f ",cl.snap.ps.origin[0]); //don't start with strca开发者_StackOverflow社区t
sprintf(tmp,"%f ",cl.snap.ps.origin[1]);strcat(pos, tmp);
fine.
with
sprintf(tmp,"%f ",cl.snap.ps.origin[0]);strcat(pos, tmp);
sprintf(tmp,"%f ",cl.snap.ps.origin[1]);strcat(pos, tmp);
not fine.
The strcat() function expects that the destination argument already contains a properly null-terminated string. In your case, it sounds like pos contains some junk that looks like a null-terminated string, but isn't what you expect. strcat() is dutifully appending on to the end of that junk.
One way to fix this is to initialise pos before your code:
pos[0] = '\0';
sprintf(tmp,"%f ",cl.snap.ps.origin[0]);strcat(pos, tmp);
sprintf(tmp,"%f ",cl.snap.ps.origin[1]);strcat(pos, tmp);
strcat concatenates strings ; which means, it merges the contents of pos and tmp. What does pos contain before you call strcat? Has it been defined?
Don't use strcat and tmp. You're writing senselessly overcomplicated and inefficient code. Instead:
pos+=sprintf(pos,"%f ",cl.snap.ps.origin[0]);
pos+=sprintf(pos,"%f ",cl.snap.ps.origin[1]);
...
Unless you're sure sprintf cannot fail, rather than directly adding the return value to pos, you should probably first store the return value in a separate int variable and check that it's not -1.
It would also be better to use snprintf to make sure you don't overflow your buffer:
size_t cnt, rem=your_buffer_size;
cnt=snprintf(pos, rem,"%f ",cl.snap.ps.origin[0]);
if (cnt>=rem) goto error;
pos+=cnt; rem-=cnt;
cnt=snprintf(pos, rem,"%f ",cl.snap.ps.origin[1]);
if (cnt>=rem) goto error;
pos+=cnt; rem-=cnt;
...
Note that cnt being an unsigned type (size_t) is critical to the error check working.
加载中,请稍侯......
精彩评论