简体   繁体   English

C ++ Map exc_bad_access(仅限Apple)

[英]C++ Map exc_bad_access (Apple only)

Code

Reads from 阅读

On Windows 7 and 8 it runs fine. 在Windows 7和8上运行正常。 However, when running in XCode 4 I get EXC_BAD_ACCESS on the second iteration when someone loads a map (select "Load Map" from title). 但是,当在XCode 4中运行时,当有人加载地图时,我会在第二次迭代时获得EXC_BAD_ACCESS(从标题中选择“加载地图”)。

You can download the source with the XCode project 您可以使用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( " \n\r" );
    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();
}

Your get_key_val function starts like this: 你的get_key_val函数如下所示:

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

It ends like this: 结尾如下:

  return key_val;
}

You're returning a pointer to a stack variable. 您正在返回指向堆栈变量的指针。 The key_val variable ceases to exist upon return from the function, so you have an invalid pointer, and the two string values in the array get destroyed. key_val变量在从函数返回时不再存在,因此您有一个无效指针,并且数组中的两个字符串值将被销毁。 Subsequent behavior is undefined. 后续行为未定义。

With move semantics in C++11 onwards, its less necessary to do this. 使用C ++ 11中的移动语义,它就不那么必要了。 You can just return std::string and the move operator should avoid any wasteful copies. 你可以只返回std :: string,移动运算符应该避免任何浪费的副本。

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

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