简体   繁体   中英

C++ Map exc_bad_access (Apple only)

Code

Reads from

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();
}

Your get_key_val function starts like this:

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. Subsequent behavior is undefined.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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