dissecting a hamster(yes a coding question)

sorry I just tried to throw a little humour in the title,

anyway I would love if someone could help dissect the hamster program used mainly on Kali linux,


I'm not going to post all the code here because it's 2000! lines of code so instead I will give the link https://github.com/robertdavidgraham/hamster/blob/master/src/cookiedb.cpp

my first question is the append function doing starting on line 36
he tests for if (m_string) but m_string is not a boolean variable so how can it be tested in an if statement?

also on the append function if this if statement is successful(I don't yet know how) why are we copying the contents of new_str to m_string and why are we then freeing m_string wouldn't this in turn end up freeing the data new_str points to??

next why is he/she making this function recursive? why the need for it ? also where is the base case ?

well thats all for now,if anybody can help me out I would be more than grateful

thanks
he tests for if (m_string) but m_string is not a boolean variable so how can it be tested in an if statement?

m_string is a pointer. In a boolean context, a null pointer is false and any other value is true (this is the same with integers: 0 is false, non-0 is true). So if (m_string) is equivalent to if (m_string != nullptr)

why are we copying the contents of new_str to m_string and why are we then freeing m_string wouldn't this in turn end up freeing the data new_str points to??

It's just freeing m_string's copy of the string. An entirely new string has been assigned to new_str, which is then assigned back to m_string after the if block. The result is that the string has been extended by a certain amount.

next why is he/she making this function recursive? why the need for it ? also where is the base case

The recursive call will definitely take the else route this time since the string has been made big enough, so that's the base case (such as it is). It seems kind of stupid, though, since it seems it would be equivalent to:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    void append(const char *str, unsigned len)
    {
        if (m_length + len >= m_max) {
            unsigned new_max = m_max*2 + 100;
            char *new_str = (char*)malloc(new_max+1);
            if (m_string) {
                memcpy(new_str, m_string, m_length + 1);
                free(m_string);
            }
            m_string = new_str;
            m_max = new_max;
        }
        memcpy(m_string+m_length, str, len);
        m_length += len;
        m_string[m_length] = '\0';
    }

Last edited on
Topic archived. No new replies allowed.