I working on a project this is my code. It compiles fine, but when I execute the program I get a runtime error. I was wondering if anyone could help me solve this or elaborate on the next steps for fixing the problem.
The program you have is a good start. The memory allocation/freeing are a bit out of order. The following is a modification of your program. It should work with pre-0.15.1 Zig.
The allocator is set up at the top level scope and passed in to each function call. Most of the allocated memory are freed up in the get() function except the returned result. It’s freed by the caller.
Cheers.
const std = @import("std");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
{
const allocator = gpa.allocator();
const res = try get(allocator, "https://example.com");
defer allocator.free(res);
std.debug.print("{s}\n", .{res});
}
if (gpa.detectLeaks()) {
std.debug.print("Memory leak detected!\n", .{});
}
}
fn get(allocator: std.mem.Allocator, a: []const u8) ![]const u8 {
const uri = try std.Uri.parse(a);
var client = std.http.Client{ .allocator = allocator };
defer client.deinit();
const server_header_buffer: []u8 = try allocator.alloc(u8, 1024 * 8);
// comment this out to see how memory leak is detected.
defer allocator.free(server_header_buffer);
var req = try client.open(.GET, uri, .{
.server_header_buffer = server_header_buffer,
});
defer req.deinit();
try req.send();
try req.finish();
try req.wait();
const body = try req.reader().readAllAlloc(allocator, 300000 * 8);
return body;
}
I am basically trying to scrape all the tickers. I get the response and then I start to parse the response with std.mem.splitScalar() function. I am a little confused on this function. I have read example on the internet but cannot figure out why this is not working. Hopefully your guy’s expertise can help me. Thanks again.
The error is telling you exactly what the issues is: splitScalar takes a single item of the element type as a delimiter, (u8 in the example), and you’re passing it a string literal.
jumpnbrownweasel solves your problem by using the correct function for your intended use.