简体   繁体   English

将String8转换为const char *

[英]Convert String8 to const char*

There's a really strange issue in a stress test. 压力测试中有一个非常奇怪的问题。 The issue can not be 100% reproduced, so I used following codes and successfully reproduced it: 无法100%复制该问题,因此我使用以下代码并成功复制了该问题:

269 >---String16 test1 = String16("0");
270 >---String16 test2 = String16("0");
271 >---String16 test3 = String16("1");
272 >---String16 test4 = String16("1");
273 >---String16 test5 = String16("12");
274 >---String8 test6  = String8("12");
275 >---const char* s1 = String8(test1).string();
276 >---PLOGI("s1: %s", s1);
277 >---const char* s2 = String8(test2);
278 >---PLOGI("s2: %s", s2);
279 >---const char* s3 = String8(test3).string();
280 >---PLOGI("s3: %s", s3);
281 >---const char* s4 = String8(test4);
282 >---PLOGI("s4: %s", s4);
283 >---const char* s5 = String8(test5);
284 >---PLOGI("s5: %s", s5);
285 >---const char* s6 = test6;
286 >---PLOGI("s6: %s", s6);

Most of the logs output are as expected: 大多数日志输出均符合预期:

2432 I/PHService(  127): s1: 0
2433 I/PHService(  127): s2: 0
2434 I/PHService(  127): s3: 1
2435 I/PHService(  127): s4: 1
2436 I/PHService(  127): s5: 12
2437 I/PHService(  127): s6: 12

But few of them are like: 但其中很少有人像:

2458 I/PHService(  127): s1: ^X
2459 I/PHService(  127): s2: ^X
2460 I/PHService(  127): s3: ^X
2461 I/PHService(  127): s4: ^X
2462 I/PHService(  127): s5: ^X
2463 I/PHService(  127): s6: 12

It seems that the data after converted was corrupted(^X is the corrupted data), but it only happened to String8(Strng16) but not to String8(). 似乎转换后的数据已损坏(^ X是损坏的数据),但仅发生在String8(Strng16)上,而没有发生在String8()上。 I'm not sure how this happened. 我不确定这是怎么发生的。 I used operator 我用过运算符

String8::operator const char*() const

which should be workable for String8(Strng16) as well. 对于String8(Strng16)也应该适用。

In the initializers of s1 , s2 ,... s5 you create temporary objects of type String8 . s1s2 ,... s5的初始化程序中,您将创建String8类型的临时对象。 Each of them is short-lived and is destroyed upon the end of the evaluation of the whole expression where it is created. 它们中的每一个都是短暂的,并且在创建整个表达式的求值结束时被销毁。

Therefore when it comes to the next line where you examine the data pointed to, the pointer is likely to point to some memory that's been already freed - and probably reused. 因此,当涉及检查所指向的数据的下一行时,该指针很可能指向一些已经释放的内存,并且有可能被重用。

String8() is most probably implemented by setting the string pointer to a static empty string buffer, therefore there's no memory to be freed. String8()最有可能是通过将字符串指针设置为静态的空字符串缓冲区来实现的,因此没有要释放的内存。

使用LOGEprintf

printf("I print a string16 '%s' ", String8(str).string());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM