Segmentation fault : Address out of bounds for a pointer in C

I am trying to build and run some complicated code that was written by someone else, I don't know who they are and can't ask them to help. The code reads a bpf (brain potential file) and converts it to a readable ascii format. It has 3 C files, and 2 corresponding header files. I got it to build successfully with minor changes, however now it crashes with a segmentation fault.

I narrowed the problem down to FindSectionEnd() (in ReadBPFHeader.c) and find that the error occurs when sscanfLine() (in the file sscanfLine.c) is called (code for both is below).

ui1 is defined as unsigned char. si1 is defined as char.

Just before returning from sscanfLine(), the address pointed to by dp is 0x7e5191, or something similar ending with 191. However, on returning to FindSectionEnd(), dp points to 0x20303035 and it says 'Address 0x20303035 is out of bounds', which then causes a fault at strstr(). The loop in FindSectionEnd() runs without problem for 14 iterations before the fault occurs. I have no idea what is going wrong. I really hope the information I have given here is adequate.

ui1 *FindSectionEnd(ui1 *dp)
{
    si1 Line[256], String[256];
    int cnt=0;
    while (sscanfLine(dp, Line) != EOF){
        dp = (ui1 *)strstr(dp, Line);
        dp+= strlen(Line);
        sscanf(Line,"%s",String);
        if(SectionEnd(String))
            return(dp);
    }
    return(NULL);
}

si1 *sscanfLine(ui1 *dp, si1 *s)
{
    int i = 0;

    *s = NULL;
    int cnt = 0;
    while (sscanf(dp, "%c", s + i) != EOF){
        cnt++;

        dp++;
        if(*(s + i) == '\n') {
            *(s + i + 1) = '\0';
            return s;
        }
        ++i;
    }
    *(s + i) = '\0';
    return s;
}

Answers


The sscanfLine function doesn't respect the size of the buffer passed in, and if it doesn't find '\n' within the first 256 bytes, happily trashes the stack next to the Line array.

You may be able to work around this by making Line bigger.

If you're going to improve the code, you should pass the buffer size to sscanfLine and make it stop when the count is reached even if a newline wasn't found. While you're at it, instead of returning s, which the caller already has, make sscanfLine return the new value of dp, which will save the caller from needing to use strstr and strlen.


Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.