0
int rtadd(IPaddr net, IPaddr mask, IPaddr gw, unsigned metric)
{
    struct route *prt, *srt, *prev;
    srt= malloc(sizeof(struct route));
    bool isdup;
    int hv = 0, i = 0;

    if (!Route.ri_valid)
        rtinit();

    prt = rtnew(net, mask, gw, metric);

    prt->rt_key = 0;
    for (i - 0; i < 32; ++i)
        prt->rt_key += (mask >> i) & 1;

    prev = NULL;
    hv = rthash(net);
    isdup = false;
    for (srt = rttable[hv]; srt; srt = srt->rt_next) //trouble point (issue with srt = rttable[hv])?
    {
        if (prt->rt_key > srt->rt_key) 
        {
            break;
        }
        if (srt->rt_net == prt->rt_net && srt->rt_mask == prt->rt_mask)
        {
            isdup = true;
            break;
        }
        prev = srt;
    }

    return 0;
}

In the above code I created a pointer srt and used a malloc command to initialize it. When I assign it to the array rttable which is declared as struct route *rttable[RT_TSIZE];, the srt pointer becomes NULL. What could be causing this?

The code which is being done for a project in my networking class is based off of Douglas Comer's TCP/IP volume II book:

https://www.amazon.com/Internetworking-TCP-Vol-Implementation-Internals/dp/0139738436

5
  • srt->rt_next (which is assigned to srt) eventually becomes null, probably. Commented Jan 31, 2017 at 21:40
  • See I thought this as well, except after testing, the srt pointer becomes NULL after directly assigning it to rttable[hv] Commented Jan 31, 2017 at 21:45
  • Then rttable[hv] is null… Commented Jan 31, 2017 at 21:45
  • I don't think so as I initialize rttable here void rtinit(void) { int i; for (i = 0; i < RT_TSIZE; ++i) rttable[i] = 0; Route.ri_bpool = malloc(sizeof(struct route)); Route.ri_valid = true; Route.ri_default = NULL; } Commented Jan 31, 2017 at 21:47
  • You initialize rttable, but you don't initialize rttable[hv] (now you posted the code, in fact, you explicitly initialize all items to 0). Commented Jan 31, 2017 at 21:48

1 Answer 1

1

The malloc is now a memory leak since you are not actually using that allocated memory address. In your for loop, you are re-assigning your src pointer to a different location in memory by pointing it to rttable[hv]. So, if you examined rttable[hv] you will most likely find it's value set to 0 or null.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.