From 0a7e2bd41772f3667ee7f264f41e7e130f4183f6 Mon Sep 17 00:00:00 2001 From: Patrick Pichler Date: Tue, 25 Apr 2023 10:57:45 +0200 Subject: [PATCH] fix: remove pointer to loop variable when searching the latest event to analyze Having a pointer to a range variable will always yield the latest value the loop sees. This leads to subtle bugs. To prevent this from happening, the range variable was assigned to a temp variable, which is then referenced as a pointer. Signed-off-by: Patrick Pichler --- cmd/serve/serve.go | 6 +++++- pkg/analyzer/events.go | 8 ++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/cmd/serve/serve.go b/cmd/serve/serve.go index ff2747bcda..6177a92478 100644 --- a/cmd/serve/serve.go +++ b/cmd/serve/serve.go @@ -76,7 +76,11 @@ var ServeCmd = &cobra.Command{ if aiProvider == nil { for _, provider := range configAI.Providers { if backend == provider.Name { - aiProvider = &provider + // he pointer to the range variable is not really an issue here, as there + // is a break right after, but to prevent potential future issues, a temp + // variable is assigned + p := provider + aiProvider = &p break } } diff --git a/pkg/analyzer/events.go b/pkg/analyzer/events.go index da12bee41f..37a9ef63f5 100644 --- a/pkg/analyzer/events.go +++ b/pkg/analyzer/events.go @@ -36,10 +36,14 @@ func FetchLatestEvent(ctx context.Context, kubernetesClient *kubernetes.Client, var latestEvent *v1.Event for _, event := range events.Items { if latestEvent == nil { - latestEvent = &event + // this is required, as a pointer to a loop variable would always yield the latest value in the range + e := event + latestEvent = &e } if event.LastTimestamp.After(latestEvent.LastTimestamp.Time) { - latestEvent = &event + // this is required, as a pointer to a loop variable would always yield the latest value in the range + e := event + latestEvent = &e } } return latestEvent, nil