在下面的程序中,tmp_data 首先打印为:“Ravindra Kumar”。但是在复制到地图后,它变成了“RRRRRRRRRRR”。当我们下次打印时,它仍然在打印“Ravindra Kumar” - 如何。它假设打印 RRRRRRRR 对吗?
#include <iostream>
#include <cstring>
#include <string>
#include <map>
using namespace std;
void fun_call( );
main(){
cout << "printing all data " << endl ;
fun_call();
fun_call();
}
void fun_call()
{
// static void *tmp_data;
void *tmp_data;
char *str="Ravindra Kumar";
char *str1="RRRRRRRRRRRRRRRRRRRRR";
char name[]="Ravi";
char value[100];
static std::map<std::string,void *> name_data_map;
std::map<std::string,void *>::iterator iter ;
iter=name_data_map.find(name) ;
if ( iter == name_data_map.end())
{
tmp_data = (void *) malloc ( strlen(str)+1 );
memcpy(tmp_data,str,strlen(str)+1);
name_data_map[name]=tmp_data;
cout << "Inside the if" << endl ;
}
cout << "Outside the if" << endl ;
iter=name_data_map.find(name) ;
memcpy(value,iter->second,strlen(str)+1);
cout << "value is " << value << endl ;
tmp_data=(void *)malloc(100000);
memcpy(tmp_data,str1,strlen(str1)+1);
}
输出 :
$ ./a.out
printing all data
Inside the if
Outside the if
value is Ravindra Kumar
Outside the if
value is Ravindra Kumar