I got an error about Segmentation fault at address [...]
when I tried to loop over a string with an allocated slice inside a custom function but I got NO error if I do the same thing in the main function.
Working code without function
The following program just iterate through a string, copy each character to an allocated slice and return the slice (which is expected to be equal to the input string).
Working code
const std = @import("std");
const testing = std.testing;
test "Same output as input" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
defer {
_= gpa.deinit();
}
const input = "abc";
std.debug.print("input: {s}\n",.{input});
//<Begin code to embed in function
const output = try allocator.alloc(u8, input.len);
defer allocator.free(output);
for (input,0..) |t,i| {
output[i] = t;
}
//>End code to embed in function
const actual = output;
std.debug.print("output: {s}\n",.{actual});
const expected = input;
try testing.expectEqualStrings(expected, actual);
}
It pass the test without problem by running zig test main.zig
.
Non-Working code
If I try to make a function doing exactly what it is written between the two comments //<Begin
and //>End
, in the snippet above, I got an error.
Error message:
zig test main2.zig
input: abc
result: { Segmentation fault at address 0x1003f9000
/Users/[...]/lib/std/fmt.zig:654:29: 0x1001bcf20 in formatType__anon_6182 (test)
for (value, 0..) |elem, i| {
^
Unwind error at address `test:0x1001bcf20` (error.InvalidUnwindInfo), trace may be incomplete
error: the following test command crashed:
/Users/[...]/.zig-cache/o/adf5dce631c4aa715277eb83a0172a35/test --seed=0x542c8295
Non working code with a function:
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
test "Same output as input" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
defer {
_= gpa.deinit();
}
const input = "abc";
std.debug.print("input: {s}\n",.{input});
const output = try returnInput(allocator,input);
std.debug.print("result: {any}\n",.{output});
const expected = input;
const actual = output;
try testing.expectEqualStrings(expected, actual);
}
pub fn returnInput(allocator: mem.Allocator, input: []const u8) mem.Allocator.Error![]u8 {
const output = try allocator.alloc(u8, input.len);
defer allocator.free(output);
for (input,0..) |t,i| {
output[i] = t;
}
return output;
}
Questions
- Why I got an error when using a function?
- How to avoid this error and pass the test?
$ zig version
0.14.0-dev.2370+5c6b25d9b