Skip to content

Instantly share code, notes, and snippets.

@askedrelic
Created February 25, 2025 23:13
Show Gist options
  • Save askedrelic/5bb129b738c2f69fe86bec2ae7dbcfa1 to your computer and use it in GitHub Desktop.
Save askedrelic/5bb129b738c2f69fe86bec2ae7dbcfa1 to your computer and use it in GitHub Desktop.
Waste memory
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
// Store allocated memory to prevent garbage collection
var memoryHogs [][]byte
// Track allocated memory
allocatedGB := 0
// Allocation chunk size (1 GB)
chunkSizeGB := 1
chunkSizeBytes := chunkSizeGB * 1024 * 1024 * 1024
fmt.Println("Starting memory allocation test...")
fmt.Println("Will allocate memory in", chunkSizeGB, "GB chunks")
// Print memory stats before we begin
printMemStats()
// Continue allocating until we fail
for {
// Try to allocate a chunk of memory
fmt.Printf("Attempting to allocate %d GB chunk...\n", chunkSizeGB)
// Allocate the memory
chunk := make([]byte, chunkSizeBytes)
// Touch the memory to ensure it's actually allocated
// (just allocating isn't enough - we need to use it)
for i := 0; i < chunkSizeBytes; i += 1024 * 1024 {
chunk[i] = 1
}
// Add to our slice to prevent garbage collection
memoryHogs = append(memoryHogs, chunk)
// Update counter
allocatedGB += chunkSizeGB
// Print status
fmt.Printf("Successfully allocated %d GB total\n", allocatedGB)
printMemStats()
// Small pause to allow for monitoring and to make the output readable
time.Sleep(1 * time.Second)
}
}
func printMemStats() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Printf("Memory stats: Alloc = %v MiB, Sys = %v MiB\n",
m.Alloc/1024/1024,
m.Sys/1024/1024)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment