If I print the value of %".2" 1 time, the program crashes but when I print it 2 times it works, I don't understand why.
I think the problem is the _aligned_free function, is there any other solution to free the allocated memory? The program works really weird when I call this function.
crashing program:
declare void @"_aligned_free"(...)
declare i32 @"printf"(...)
define i32 @"main"()
{
entry:
%".2" = alloca i32
store i32 534, i32* %".2"
%".4" = alloca [4 x i8]
store [4 x i8] c"%d\0a\00", [4 x i8]* %".4"
%".6" = load i32, i32* %".2"
%".7" = call i32 (...) @"printf"([4 x i8]* %".4", i32 %".6")
call void (...) @"_aligned_free"(i32* %".2")
%".9" = alloca [4 x i8]
store [4 x i8] c"%s\0a\00", [4 x i8]* %".9"
%".11" = alloca [9 x i8]
store [9 x i8] c"sdgfsdfg\00", [9 x i8]* %".11"
%".13" = call i32 (...) @"printf"([4 x i8]* %".9", [9 x i8]* %".11")
%".14" = alloca i32
store i32 534, i32* %".14"
%".16" = alloca [4 x i8]
store [4 x i8] c"%d\0a\00", [4 x i8]* %".16"
%".18" = load i32, i32* %".14"
%".19" = call i32 (...) @"printf"([4 x i8]* %".16", i32 %".18")
call void (...) @"_aligned_free"(i32* %".14")
%".21" = alloca [4 x i8]
store [4 x i8] c"%s\0a\00", [4 x i8]* %".21"
%".23" = alloca [9 x i8]
store [9 x i8] c"sdgfsdfg\00", [9 x i8]* %".23"
%".25" = call i32 (...) @"printf"([4 x i8]* %".21", [9 x i8]* %".23")
ret i32 0
}
I think the problem is the _aligned_free function, is there any other solution to free the allocated memory?
Yes, that's the problem. aligned_free() requires memory you got from malloc() or similar functions which allocate from the heap. It cannot take a pointer to your stack.
alloca() (and LLVM's alloca
instruction) allocate space from your stack, which is freed exactly when your function ends, you can't release the memory any earlier or later than that.
You could use call i8* @malloc(i32 9)
to create memory instead of using alloca
. That will allow you to control the lifetime of the memory manually, and you must remember to call free() on it.
You could mark the alloca
s dead using call void @llvm.lifetime.end(i64 <size>, ptr %ptr)
and while that won't cause stack memory to be freed, it may cause it to be reused with other stack memory, by figuring out that you don't need them both at the same time.