Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my string losing its value?

For some reason, the value of my toCheck variable is getting erased and I have no idea why. Any suggestions?

bool
check(string toCheck){
    printf("toCheck: %s\n", toCheck.c_str());
    ifstream list;
    list.open("list.txt");
    string temp;
    while(list){
        getline(list,temp);
        printf("toCheck: '%s' temp: '%s'\n",toCheck.c_str(), temp.c_str());
        if(temp == toCheck){
            printf("Username exists\n");
            return false;
        }
    }
    printf("returning true\n");
    return true;
}

Here's what it is being passed: TestTrevor

And here's the output:

toCheck: TestTrevor  
toCheck: '' temp: 'Trevor'  
toCheck: '' temp: ''  

Username exists
like image 612
Trevor Avatar asked Apr 23 '12 23:04

Trevor


1 Answers

From your comments:

It's really hard to debug (which is why I'm using printf) because I'm forking and using processes (this is a server for a VoIP project I'm working on) and the gdb wasn't working when I tried to follow the child process.

Emphasis mine.

I would not be surprised if the memory dynamically allocated for toCheck never really made it into the forked process, or made it but was somehow discarded / overwritten.

NEW INFO: if I comment out the getLine(list, temp); then it doesn't erase toCheck, any thoughts?

This is the very first time in your program that the std::allocator is required to actually allocate memory.


The STL has never been developped with forking in mind, so it is perfectly possible than it simply does not work in this usecase.

You could check what's going on with a debugger. See at which address the memory for toCheck is allocated and what happens when memory is allocated for temp, but it's deep diving.

Since it seems you have issues with gdb, you can try dumping the addresses first (printf("%x", &toCheck[0]);).

like image 57
Matthieu M. Avatar answered Sep 27 '22 18:09

Matthieu M.