096_memory_allocation.zig 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //
  2. // In most of the examples so far, the inputs are known at compile
  3. // time, thus the amount of memory used by the program is fixed.
  4. // However, if responding to input whose size is not known at compile
  5. // time, such as:
  6. // - user input via command-line arguments
  7. // - inputs from another program
  8. //
  9. // You'll need to request memory for your program to be allocated by
  10. // your operating system at runtime.
  11. //
  12. // Zig provides several different allocators. In the Zig
  13. // documentation, it recommends the Arena allocator for simple
  14. // programs which allocate once and then exit:
  15. //
  16. // const std = @import("std");
  17. //
  18. // // memory allocation can fail, so the return type is !void
  19. // pub fn main() !void {
  20. //
  21. // var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
  22. // defer arena.deinit();
  23. //
  24. // const allocator = arena.allocator();
  25. //
  26. // const ptr = try allocator.create(i32);
  27. // std.debug.print("ptr={*}\n", .{ptr});
  28. //
  29. // const slice_ptr = try allocator.alloc(f64, 5);
  30. // std.debug.print("slice_ptr={*}\n", .{slice_ptr});
  31. // }
  32. // Instead of an simple integer or a constant sized slice, this
  33. // program requires a slice to be allocated that is the same size as
  34. // an input array.
  35. // Given a series of numbers, take the running average. In other
  36. // words, each item N should contain the average of the last N
  37. // elements.
  38. const std = @import("std");
  39. fn runningAverage(arr: []const f64, avg: []f64) void {
  40. var sum: f64 = 0;
  41. for (0.., arr) |index, val| {
  42. sum += val;
  43. const f_index: f64 = @floatFromInt(index + 1);
  44. avg[index] = sum / f_index;
  45. }
  46. }
  47. pub fn main() !void {
  48. // pretend this was defined by reading in user input
  49. var arr: []const f64 = &[_]f64{ 0.3, 0.2, 0.1, 0.1, 0.4 };
  50. // initialize the allocator
  51. var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
  52. // free the memory on exit
  53. defer arena.deinit();
  54. // initialize the allocator
  55. const allocator = arena.allocator();
  56. // allocate memory for this array
  57. var avg: []f64 = ???;
  58. runningAverage(arr, avg);
  59. std.debug.print("Running Average: ", .{});
  60. for (avg) |val| {
  61. std.debug.print("{d:.2} ", .{val});
  62. }
  63. std.debug.print("\n", .{});
  64. }
  65. // For more details on memory allocation and the different types of
  66. // memory allocators, see https://www.youtube.com/watch?v=vHWiDx_l4V0