076a_memory_allocation.zig 2.4 KB

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