开发者

Why does strcat() on a new string craps out undefined characters in the beginning while strcpy is ok?

开发者 https://www.devze.com 2023-01-10 01:19 出处:网络
For example sprintf(pos,\"%f \",cl.snap.ps.origin[0]); //don\'t start with strca开发者_StackOverflow社区t

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消