This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: map usage woes


Srikanth Vedire <srvedire@yahoo.com> writes:

> Hello,
> 
> I seem to have a simple problem.. Why are the results
> after running this program different than expected?
> 
> I get
> [1] = (null) // instead of 100
> [2] = 200 
> [3] = 300
> 
> Hopefully someone can tell me what I'm doing wrong.
> I'm using 2.95.3 20010315 release of gcc.
> 
> Srikanth
> 
> #include <iostream>
> #include <map>
> 
> struct ltstr
> {
>   bool operator()(const char* s1, const char* s2)
> const
>   {
>     return strcmp(s1, s2) < 0;
>  }
>};
> 
> 
> typedef map<const char *, const char *, ltstr>
> CharCharMap;
> 
> int main(int argc, char *argv[])
> {
>     char buff[20];
> 
>     CharCharMap temp2;
> 
>     buff[0] = '1';
>     buff[1] = '\0';
>     temp2[(const char *)buff] = "100";
>     buff[0] = '2';
>     buff[1] = '\0';
>     temp2[buff] = "200";
>     temp2["3"] = "300";
> 
>     cout << "[1] = " << temp2["1"] << endl;
>     cout << "[2] = " << temp2["2"] << endl;
>     cout << "[3] = " << temp2["3"] << endl;

You've touched buff, which is currently in the map (It's not making a
copy of buff, only it's pointer. It has no idea how to copy const char
*'s).  This is a no-no.

This program should actually segfault, and under g++-3.0, it does.

Try

temp2[strdup(buff)] = "100";
and temp2[strdup(buff)] = "200";
where you have
temp2[(const char *)buff] = "100";
and  temp2[buff] = "200";


-- 
"I went into a clothes store the other day and a salesman walked
up to me and said, "Can I help you?"  and I said "Yeah, do you
got anything I like?"  He said, "What do you mean do we have
anything you like?"  I said, "You started this."
"-Steven Wright


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]