Skip to content

Concurrent Append to Slice

Description

Appending to a slice from multiple goroutines is not concurrency safe, which can lead to a race condition. This occurs when multiple goroutines attempt to append to the same slice simultaneously, resulting in unpredictable behavior.

Examples

Insecure Code

go
var slice []int
for i := 0; i < 10; i++ {
    go func() {
        slice = append(slice, 1)
    }()
}

Secure Code

go
var slice []int
var mutex sync.Mutex
for i := 0; i < 10; i++ {
    go func() {
        mutex.Lock()
        slice = append(slice, 1)
        mutex.Unlock()
    }()
}

Remediation

Use a mutex to synchronize access to the slice, ensuring that only one goroutine can append to it at a time.

Rule Details

FieldValue
IDCODE-0094
CategoryConcurrency
SeverityHIGH
CWECWE-362
ConfidenceMEDIUM
ImpactMEDIUM
LikelihoodHIGH
ExploitabilityEASY
Tagsrace condition, concurrency
OWASPN/A

References