I am running this on M1 Pro, under macOS Ventura 13.4
var x = strdup("ABC Hello, World! Hello, World!!, Hello, World!!!")!
print(x[0]) // 65
print(x[1]) // 66
print(x[2]) // 67
free(x)
print(x[0]) // -24
print(x[1]) // -65
print(x[2]) // -34
I expected to get 0's after free, tried in both Debug & Release. Is this a bug? Or perhaps I am not testing this properly, in which case would appreciate the fix. Thank you.
Edit 1:
Tried this modification to not cause any potential allocation between free and reading the freed memory out, but the result is the same:
var x = strdup("ABC Hello, World! Hello, World!!, Hello, World!!!")!
var a = 0, b = 0
memmove(&a, x, 8)
free(x)
memmove(&b, x, 8)
print(String(format: "%016lx, ", a)) // 6c6c654820434241, as expected
print(String(format: "%016lx, ", b)) // 0000beaddfdd00c0, expected to see 0's here
Edit 2:
Or do you mean the memory it is cleaned, but I should just disregard the first pointer or so? hmm, let me double check that.
Edit 3:
Indeed!
var x = strdup("ABC Hello, World! Hello, World!!, Hello, World!!!")!
var a = 0, b = 0
memmove(&a, x+16, 8)
free(x)
memmove(&b, x+16, 8)
print(String(format: "%016lx, ", a)) // 2c6f6c6c65482021, as expected
print(String(format: "%016lx, ", b)) // 0000000000000000 as expected