Segmentation violation with golang channels

13,424

You do not check for any error when calling the api. Thus the error when trying to close a response that never arrived.

This code does not panic:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    requests := 10000
    ch := make(chan string, requests)
    for i := 1; i <= requests; i++ {
        go func(iter int) {
            fmt.Println(iter)
            resp, err := http.Get("http://localhost:8080/api/project")
            if (err == nil) {
              resp.Body.Close()
            }
            ch <- fmt.Sprint(iter)
        }(i)
    }
    for i := 1; i <= requests; i++ {
        fmt.Println(<-ch)
    }
}
Share:
13,424
Tim Ferrell
Author by

Tim Ferrell

By Day: Building products for the clouds. By Night: Helping out on Stack Overflow. For Fun: Traveling

Updated on June 05, 2022

Comments

  • Tim Ferrell
    Tim Ferrell almost 2 years

    The below code opens 10,000 go routines, which make HTTP calls, get the response, close the response, and write to a channel with an ID.

    In the second for loop, it prints out from that buffered channel the ID of the previous go routine.

    This causes a segmentation violation, and I can't figure out why.

    Panic:

    panic: runtime error: invalid memory address or nil pointer dereference
    [signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x2293]
    

    Code:

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    func main() {
        requests := 10000
        ch := make(chan string, requests)
        for i := 1; i <= requests; i++ {
            go func(iter int) {
                fmt.Println(iter)
                resp, _ := http.Get("http://localhost:8080/api/project")
                resp.Body.Close()
                ch <- fmt.Sprint("%i", iter)
            }(i)
        }
        for i := 1; i <= requests; i++ {
            fmt.Println(<-ch)
        }
    }