开发者

is it possible snprintf return char array beginning with '\0'?

I have the f开发者_JAVA技巧ollowing code :

string getid()
{   
    pthread_t tid = pthread_self();
    struct timeval tv;
    gettimeofday(&tv, NULL);
    uint64_t t = static_cast<uint64_t>(tv.tv_sec);
    char buf[64];
    snprintf(buf, 64, "%ld-%ld", static_cast<uint64_t>(tid), static_cast<uint64_t>(t));

    return buf;
}

sometimes, the returned string has 0 size(), I think one possible reason is buf[0] is '\0', that means pthread_self return '\0' beginning char array?


pthread_self returns a pthread_t, which is not necessarily an integer type. So your cast might not even make sense.

Next, %ld refers to a long int, but you're passing uint64_t values. Depending on the size of a long int on your system, that might again not make much sense.

But, to get to your question : check the return value of the snprintf call : it returns the number of characters that have been successfully written. If it's not at least 3, then something went wrong.


to printf a 64bit number, it is not %ld. The most portable is using the very ugly PRIu64 like:

printf("%"PRIu64"\n", u64); 

But I think %llu might also work on your platform.

As other have pointed out, you are returning a pointer to an auto array, meaning it will reside in temporary storage (can in some cases not be the stack). Either return the pointer to an array allocated by new or if you do not need to be reentrant, declare the buffer static, but this is not a very good solution, allocating it on the heap with new would be preferred.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜