Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang segmentation fault (core dumped)

Tags:

go

I'm new to golang and programming.

I have written a small program that moves files matching a regex from one directory to another.

The program runs successfully on ubuntu 16.04 and on a Centos 6.8 (Final)

On a certain Centos machine (I don't know the exact version of that one. I do know it is 6.? and it is lower than 6.8), I get:

Segmentation fault (core dumped)

My research shows that this error occurs when the OS does not allow me to access memory.

Can somebody tell me where it goes wrong in my code. Also please point out bad practices if you see any.

package main

import (
    "flag"
    "fmt"
    "log"
    "os"
    "regexp"
    "strings"
)

func main() {

    batch := flag.Int("batch", 0, "the amount of files to be processed")
    pattern := flag.String("pattern", "", "string pattern to be matched")
    dir := flag.Int("dir", 0, "key from strings.Split(pattern, '')")
    confirm := flag.String("move", "no", "flags if program should move files")

    flag.Parse()

    d, err := os.Open(".")
    if err != nil {
        log.Fatal("Could not open directory. ", err)
    }

    files, err := d.Readdir(*batch)
    if err != nil {
        log.Fatal("Could not read directory. ", err)
    }

    for _, file := range files {
        fname := file.Name()
        match, err := regexp.Match(*pattern, []byte(fname))
        if err != nil {
            log.Fatal(err)
        }
        if match == true {

            s := strings.Split(fname, "_")
            dest := s[*dir]

            switch *confirm {
            case "no":
                fmt.Printf(" %s  matches  %s\n Dir name =  %s\n -----------------------\n", fname, *pattern, dest)

            case "yes":
                //all directories are expected to be a number.
                //terminate execution if directory doesn't match regex
                if match, err := regexp.Match("[0-9]", []byte(dest)); match == false {
                    log.Fatalf("Expected directory name does not match prepared directory.\n Expected dir name must be a number (regex [0-9]) | Current dir name is: %s\n", dest)
                    if err != nil {
                        log.Fatal(err)
                    }
                }

                //check if direcotry exists. create it if it doesn't
                if _, err := os.Stat(dest); os.IsNotExist(err) {
                    err = os.Mkdir(dest, 0777)
                    if err != nil {
                        log.Fatal("Could not create directory. ", err)
                    }
                }
                err = os.Rename(fname, fmt.Sprintf("%s/%s", dest, fname))
                if err != nil {
                    log.Fatal("Could not move file. ", err)
                }
                fmt.Printf("Moved %s to %s\n", fname, dest)
            }
        }
    }
    fmt.Println("Exit")
}
like image 657
user3017869 Avatar asked Nov 12 '16 11:11

user3017869


People also ask

Is segmentation fault a core dump?

Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” When a piece of code tries to do read and write operation in a read only location in memory or freed block of memory, it is known as core dump.


1 Answers

My first guess would be you are over-running the bounds of the 's' array:

dest := s[*dir]

I added some safety checks (see [Added]):

package main

import (
    "flag"
    "fmt"
    "log"
    "os"
    "regexp"
    "strings"
)

func main() {
    batch := flag.Int("batch", 0, "the amount of files to be processed")
    pattern := flag.String("pattern", "", "string pattern to be matched")
    dir := flag.Int("dir", 0, "key from strings.Split(pattern, '')")
    confirm := flag.String("move", "no", "flags if program should move files")

    flag.Parse()

    d, err := os.Open(".")
    if err != nil {
        log.Fatal("Could not open directory. ", err)
    }
    defer d.Close() // [Added] probably not needed if a directory but doesn't hurt

    files, err := d.Readdir(*batch)
    if err != nil {
        log.Fatal("Could not read directory. ", err)
    }

    for _, file := range files {
        fname := file.Name()
        match, err := regexp.Match(*pattern, []byte(fname))
        if err != nil {
            log.Fatal(err)
        }
        if match == true {
            s := strings.Split(fname, "_")

            // [Added] Sanity check *dir index before using
            if *dir >= len(s) {
                log.Fatalf("dir is out of range: dir=%d len(s)=%d\n", *dir, len(s))
            }

            dest := s[*dir]

            switch *confirm {
            case "no":
                fmt.Printf(" %s  matches  %s\n Dir name =  %s\n -----------------------\n", fname, *pattern, dest)

            case "yes":
                //all directories are expected to be a number.
                //terminate execution if directory doesn't match regex
                if match, err := regexp.Match("[0-9]", []byte(dest)); match == false {
                    log.Fatalf("Expected directory name does not match prepared directory.\n Expected dir name must be a number (regex [0-9]) | Current dir name is: %s\n", dest)
                    if err != nil {
                        log.Fatal(err)
                    }
                }

                //check if direcotry exists. create it if it doesn't
                if _, err := os.Stat(dest); os.IsNotExist(err) {
                    err = os.Mkdir(dest, 0777)
                    if err != nil {
                        log.Fatal("Could not create directory. ", err)
                    }
                }
                err = os.Rename(fname, fmt.Sprintf("%s/%s", dest, fname))
                if err != nil {
                    log.Fatal("Could not move file. ", err)
                }
                fmt.Printf("Moved %s to %s\n", fname, dest)

                // [Added]: Make sure to handle non 'yes/no' answers
            default:
                log.Fatalf("confirm is invalid '%s'\n", *confirm)
            }
        }
    }
    fmt.Println("Exit")
}

Not sure what you're inputting to the program but nothing else I can see would cause a segmentation fault.

like image 52
Josh Lubawy Avatar answered Nov 15 '22 10:11

Josh Lubawy