在嵌入式 Linux 平台上使用 std::string 时出现段错误

2023-12-01

我已经花了几天时间来解决我的应用程序在嵌入式 Arm Linux 平台上运行的问题。不幸的是,该平台阻止我使用任何常用的有用工具来查找确切的问题。当相同的代码在运行 Linux 的 PC 上运行时,我没有收到这样的错误。

在下面的示例中,我可以通过取消注释字符串、列表或向量行来可靠地重现问题。让他们评论会导致应用程序运行完成。我预计有什么东西正在破坏堆,但我看不到是什么?该程序将运行几秒钟,然后出现分段错误。

使用arm-linux交叉编译器编译代码:

arm-linux-g++ -Wall -otest fault.cpp -ldl -lpthread
arm-linux-strip test

任何想法都非常感激。

#include <stdio.h>
#include <vector>
#include <list>
#include <string>

using namespace std;
/////////////////////////////////////////////////////////////////////////////

class TestSeg
{
 static pthread_mutex_t     _logLock;

 public:
  TestSeg()
  {
  }

  ~TestSeg()
  {
  }

  static void* TestThread( void *arg )
  {
   int i = 0;
   while ( i++ < 10000 )
   {
    printf( "%d\n", i );
    WriteBad( "Function" );
   }
   pthread_exit( NULL );
  }

  static void WriteBad( const char* sFunction )
  {
   pthread_mutex_lock( &_logLock );

   printf( "%s\n", sFunction );
   //string sKiller;     //       <----------------------------------Bad
   //list<char> killer;    //       <----------------------------------Bad
   //vector<char> killer;    //       <----------------------------------Bad

   pthread_mutex_unlock( &_logLock );
   return;
  }

  void RunTest()
  {
   int threads = 100;
   pthread_t     _rx_thread[threads];
   for ( int i = 0 ; i < threads ; i++ )
   {
    pthread_create( &_rx_thread[i], NULL, TestThread, NULL );
   }

   for ( int i = 0 ; i < threads ; i++ )
   {
    pthread_join( _rx_thread[i], NULL );
   }
  }

};

pthread_mutex_t       TestSeg::_logLock = PTHREAD_MUTEX_INITIALIZER;


int main( int argc, char *argv[] )
{
 TestSeg seg;
 seg.RunTest();
 pthread_exit( NULL );
}

也许您正在使用标准库的单线程版本,包括new and delete运营商?

这些对象是在互斥锁的保护范围内构造的,但在这些边界之外被破坏,因此析构函数可能会互相踩踏。一项快速测试是放置范围括号{}围绕声明killer.

See 海湾合作委员会文档了解更多。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在嵌入式 Linux 平台上使用 std::string 时出现段错误 的相关文章

随机推荐