std::string::assign 崩溃的问题
生活随笔
收集整理的這篇文章主要介紹了
std::string::assign 崩溃的问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近遇到了一個assign 崩潰的問題, 代碼的話 其實就是去assign,莫名其妙就崩潰,是在一個自動化測試的時候發生的,可能手動測試的時候不會發現!
猜了一下里面的assign的邏輯,基本是這樣的:每次去assign的時候 string內部會去申請內存,然后把數據放進去,第二次的話 會首先將之前的先delete掉,再重新new一遍!
那樣的話 多線程就有問題了,因為這個東西的話 本身不是線程安全的,測試代碼如下,希望可以幫助到遇到這個問題的同學!~
#include <pthread.h> #include <unistd.h> #include <stdio.h> #include<string> std::string g_str;void* test(void*) {while(1){std::string str ="123456";g_str.assign(str);} }int main() {pthread_t t1;pthread_create(&t1, NULL, test, NULL); usleep(50);while(1){std::string str ="123456";g_str.assign(str);}return 0; }堆棧如下 Program received signal SIGABRT, Aborted. 0x00007ffff70141d7 in raise () from /lib64/libc.so.6 Missing separate debuginfos, use: debuginfo-install glibc-2.17-157.el7_3.2.x86_64 libgcc-4.8.5-11.el7.x86_64 libstdc++-4.8.5-11.el7.x86_64 (gdb) thread apply all btThread 2 (Thread 0x7ffff6fde700 (LWP 2545)): #0 0x00007ffff705c284 in _int_malloc () from /lib64/libc.so.6 #1 0x00007ffff705efbc in malloc () from /lib64/libc.so.6 #2 0x00007ffff79170cd in operator new(unsigned long) () from /lib64/libstdc++.so.6 #3 0x00007ffff7975c79 in std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) () from /lib64/libstdc++.so.6 #4 0x00007ffff7977531 in char* std::string::_S_construct<char const*>(char const*, char const*, std::allocator<char> const&, std::forward_iterator_tag) () from /lib64/libstdc++.so.6 #5 0x00007ffff7977968 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) () from /lib64/libstdc++.so.6 #6 0x0000000000400b90 in test () at test1.cpp:12 #7 0x00007ffff7bc8dc5 in start_thread () from /lib64/libpthread.so.0 #8 0x00007ffff70d676d in clone () from /lib64/libc.so.6Thread 1 (Thread 0x7ffff7fe9740 (LWP 2541)): #0 0x00007ffff70141d7 in raise () from /lib64/libc.so.6 #1 0x00007ffff70158c8 in abort () from /lib64/libc.so.6 #2 0x00007ffff7053f07 in __libc_message () from /lib64/libc.so.6 #3 0x00007ffff705b503 in _int_free () from /lib64/libc.so.6 #4 0x00007ffff797704e in std::string::assign(std::string const&) () from /lib64/libstdc++.so.6 #5 0x00000000004009bd in main () at test1.cpp:28 (gdb) 其實已經很清楚了!總結
以上是生活随笔為你收集整理的std::string::assign 崩溃的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深度学习常见算法之训练自己的数据
- 下一篇: 逻辑回归与正则化