The Anatomy of a Segmentation Fault – A real life example

Posted on


Screen Shot 2018-03-26 at 11.08.40 AM.png

I was browsing and came across a user running into a segmentation fault in their programming assignment. This problem looked like an ideal case for static analysis. The author was struggling with correct use of pointers but still had a compilable and runnable program.

The code causing the segmentation fault is in the function filecopy():

void filecopy(int infd, int outfd) {
    char *buf;
    while(read(infd, buf, 1) != -1)
        write(outfd, buf, sizeof(buf));


Astute readers will detect the missing memory allocation for buf (and the lack of reasonable bounds on the size of buf as well.) However, CodeSonar also detected another issue with the use of sprintf() in the main program:

char tmp[30];
sprintf(tmp, "%s: can't open %s", prog, *argv);
write(STDOUT_FILENO, &tmp, sizeof(tmp));   

Again, our readers likely picked up on the potential buffer overrun condition possible with the array tmp for large strings stored at *argv. Although this wasn’t an immediate concern for the programmer, it does point out a common programing mistake that can not only cause programs to crash but it’s also possible security vulnerability (e.g. CWE-121 Stack-based buffer overflow.)

Let’s take a look at CodeSonar’s output for the example code from this problem:


CodeSonar points out the possible buffer overrun at line 20 and the uninitialized variable at line 35.

Although both of these issues are detectable by experienced programmers, it’s not always easy to detect and solve issues like these. Sometimes a variable source maybe in a different compilation unit with several call layers before its eventual use. In addition, seemingly innocuous use of user input directly into functions that don’t limit string length, for example, open up a program to misuse. The moral of the story here is that static analysis found these errors simply and easily and corroborated the other experts opinions on StackOverflow.

Related Posts

Check out all of CodeSecure’s resources and stay informed.

view all posts

Book a Demo

We’re ready to help you integrate SAST and SCA security into your DevSecOps flow. Get a personally guided tour of our solution offerings to ensure you are receiving the right solution for your development team. 

book now