欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

std::string::assign 崩溃的问题

发布时间:2025/3/15 编程问答 40 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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 崩溃的问题的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。