Difference between char* and string in terms of map usage

Hi all,
I am currently storing '|' separated value in a file and again try to retrieve it. Below is snippets of my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
std::map<int, char*> symbolMap
.
.
.

void MyClass :: readDumpFile(char* fileName)
{
  FILE *fd;  
  char        mystring [150];
  RWCString   token;
  
  fd  = fopen(fileName,"r");
  
  if(fd == NULL)
  {
    slog(Info)<<"Error in open "<<fileName<<" file in readDumpFile function "<<endlog;
    return;
  }
  while(!feof (fd))
  {
    fgets(mystring,500,fd); 
    RWCString line(mystring);
    RWCTokenizer parse(line);
    token = parse("|");

    int securityIndex;
    if(! token.isNull() )
      securityIndex = atoi(token); 
    else
      continue;
    token = parse("|");

    char *security;
    if(! token.isNull() )
      security = (char*)token.data(); 
    else
      continue;

    symbolMap[securityIndex] = security;
    
  }
  fclose(fd);
}
.
.
.

char* MyClass :: getSymbolFromSymbolMap(int index)
{
  std::map<int,char *>::iterator itr;
  itr = symbolMap.find(index); 
  if(itr != symbolMap.end() )
    return itr->second;
  else
    return NULL;
}


Here i am putting value in map through readDumpFile() function, and retrieving it through getSymbolFromSymbolMap() function. When i try to find on particular value in map, i am able to get the value through iterator , but the value which i get(char *) is garbage value . But if i use std::map<int, char*> symbolMap instead of char* one then i am able to get proper value.
Can anyone explain why i am getting garbage value in first case?

Thanxs in advancd.
You're storing a pointer to an object that's destroyed long after you want to reference it. Perhaps you could consider mapping int to a string.
But i was under impression that std::map 's alloc method allocate memory to key and value, I thought it would allocate value to char *.
It does accomodate a char*, and assigns the correct value too.

The problem is that once you've gone around the loop, you reassign token's value. The pointer you've stored in the map now no longer points to what you think it points to. That string you set it up to point to is gone.
The allocator allocates memory for the char* itself, not what it points to.
@kbw , @L B thanks for the explanation man .
Correct me if i am wrong , If i allocate memory to token , then we will be able to resolve the issue.Right?
Yes, but then you'll have to manage that memory. Using a string effectively deals with that in an exception safe way.
You could use map<int, RWCString> as well, since you're already using RogueWave strings elsewhere.
Topic archived. No new replies allowed.