[英]C++ Map exc_bad_access (Apple only)
在Windows 7和8上运行正常。 但是,当在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( " \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();
}
你的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,移动运算符应该避免任何浪费的副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.