C++映射 exc_bad_access(仅限 Apple)
在 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();
}
On Windows 7 and 8 it runs fine. 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).
You can download the source with the XCode project
#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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
get_key_val
函数是这样开始的:它的结束是这样的:
您返回一个指向堆栈变量的指针。从函数返回后,
key_val
变量不再存在,因此指针无效,并且数组中的两个字符串值被破坏。后续行为是未定义的。Your
get_key_val
function starts like this:It ends like this:
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. Subsequent behavior is undefined.对于 C++11 及以上版本中的移动语义,这样做的必要性降低了。您可以只返回 std::string 并且移动运算符应该避免任何浪费的副本。
With move semantics in C++11 onwards, its less necessary to do this. You can just return std::string and the move operator should avoid any wasteful copies.