doulubashang6936 2016-11-12 11:47
浏览 59

Golang分段错误(核心已转储)

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
 Dir name =  %s
 -----------------------
", 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.
 Expected dir name must be a number (regex [0-9]) | Current dir name is: %s
", 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
", fname, dest)
            }
        }
    }
    fmt.Println("Exit")
}
  • 写回答

1条回答 默认 最新

  • douyan4900 2017-01-19 09:47
    关注

    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
    ", *dir, len(s))
                }
    
                dest := s[*dir]
    
                switch *confirm {
                case "no":
                    fmt.Printf(" %s  matches  %s
     Dir name =  %s
     -----------------------
    ", 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.
     Expected dir name must be a number (regex [0-9]) | Current dir name is: %s
    ", 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
    ", fname, dest)
    
                    // [Added]: Make sure to handle non 'yes/no' answers
                default:
                    log.Fatalf("confirm is invalid '%s'
    ", *confirm)
                }
            }
        }
        fmt.Println("Exit")
    }
    

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

    评论

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错