0

This given code in server.c gets the slice of string up to an appearance of \n.

    const char* haystack = request;
    char* needle = strstr(haystack, "\r\n");
    if (needle == NULL)
    {
        error(400);
        continue;
    }
    else if (needle - haystack + 2 > LimitRequestLine)
    {
        error(414);
        continue;
    }   
    char line[needle - haystack + 2 + 1];
    strncpy(line, haystack, needle - haystack + 2);
    line[needle - haystack + 2] = '\0';

But since we need to do a lot of looking for spaces etc., I tried doing some of the same sort of stuff inside a function. Which led to trouble.

E.g. this is supposed to return the position of a substring, or -1 if it doesn't appear:

int whereis(string fodder, string sub)
{
    const char* hay = fodder;
    char* need = strstr(hay, sub);
    if (need == NULL)
    {
        return -1;
    }
    else
    {
    return need - hay;
    }
}

This seems to work OK if sub does occur in fodder but if not, I get a segmentation fault instead of a return of -1. What is going wrong?

4
  • OK, after some more testing the problem seems to be partly with using GetString to set up the string passed as "fodder". When I set this string directly using char* line = "asdfg"; and then pass "line" as the argument "fodder", all seems well. I'd still like to know what is going wrong though.
    – bunstance
    Mar 16, 2015 at 14:01
  • I don't think the whereis function per sey is the one that's causing the segmentation fault, but rather, the fact that you used a string literal to initialize a char * and maybe doing some modifications to that string afterwards. If that's the case, then you got a segmentation fault because you can't modify the contents of a string literal because they are constant values.
    – kzidane
    Mar 16, 2015 at 15:11
  • Also, this maybe irrelevant to your question, but I'm not really sure why you're returning need - hay since this basically returns the length of the string before your substring. If this is what you want, then maybe the name whereis is a bit misleading.
    – kzidane
    Mar 16, 2015 at 15:14
  • Thanks, it certainly does seem to be the prior history of the "fodder" to blame. I seem to have cured the problem but I wish I knew exactly what was wrong!. Possibly "whereis" is a bad name but, yes, it's just supposed to find the position of the substring.
    – bunstance
    Mar 17, 2015 at 8:10

0

You must log in to answer this question.

Browse other questions tagged .