C++映射exc_bad_access(仅限苹果)

C++ Map exc_bad_access (Apple only)

本文关键字:苹果 access 映射 exc bad C++      更新时间:2023-10-16

代码

从读取

在Windows7和Windows8上运行良好。然而,当在XCode 4中运行时,当有人加载地图时,我在第二次迭代中得到EXC_BAD_ACCESS(从标题中选择"加载地图")。

您可以使用XCode项目下载源代码

#include <string>
#include <map>
#include <iostream>
std::map <std::string, std::string> info;    
std::string* get_key_val( std::string* line )
{
    std::string key_val[2];
    int start, end;
    start = line->find_first_not_of( " " );
    end = line->find_last_of( ":" );
    if( start == -1 )
    {
        return NULL;
    }
    else if( end == -1 )
    {
        return NULL;
    }
    else
    {
        key_val[0] = line->substr( start, end - start );
    }
    start = line->find_first_not_of(" ", end + 1);
    end = line->find_last_of( " nr" );
    if( start == -1 )
    {
        return NULL;
    }
    else if( end == -1 )
    {
        return NULL;
    }
    else
    {
        key_val[1] = line->substr( start, end - start );
    }
    return key_val;
}

void parse_from_line( std::string* line )
{
    std::string* keyv = get_key_val( line );
    if( keyv[0].empty() == false && keyv[1].empty() == false ) info[ keyv[0] ] = keyv[1];
}
int main( int argc, char* args[] )
{
    std::string line = "name: Foo";
    parse_from_line( &line );
    std::cout << "Hello " << info["name"].c_str();
}

get_key_val函数的启动方式如下:

std::string* Map::get_key_val( std::string* line )
{
  std::string key_val[2];

结局是这样的:

  return key_val;
}

您正在返回一个指向堆栈变量的指针。函数返回后,key_val变量将不存在,因此您有一个无效的指针,数组中的两个字符串值将被销毁。后续行为未定义。

随着C++11中的移动语义的发展,这样做的必要性降低了。您只需返回std::string,move操作符就可以避免任何浪费的副本。