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
| Field | Value |
|---|---|
| ID | CODE-0094 |
| Category | Concurrency |
| Severity | HIGH |
| CWE | CWE-362 |
| Confidence | MEDIUM |
| Impact | MEDIUM |
| Likelihood | HIGH |
| Exploitability | EASY |
| Tags | race condition, concurrency |
| OWASP | N/A |