1

I am calling a C function from LLVM code, which allocates some space for a string like this: (char *) malloc(..len..);

This mallocated value in %0 then stored in stack variable %something.

define i8* @someFun() {
entry:
  %something = alloca i8*, align 8
  
  ; mallocing some space for a string
  %0 = call i8* @<function-using-malloc>()
  store i8* %0, i8** %something, align 8
  
  ; freeing heap space
  %1 = call i8* @free(i8* %0)

  %2 = load i8*, i8** %something, align 8
  ret i8* %2
}

After the store instruction, I am freeing %0 and then returning %something from the function.

Then after receiving the returned value from someFun(), the value is still available in main(), however I'm guessing it should have been freed?

define i32 @main() {
entry:
    ; printing value here correctly after free
    %0 = call i8* @someFun()
    ..printing %0..
    
    ret i32 0
}

I'm probably missing some memory management knowledge, so my question is what happens before and after freeing %0 in this case? Is this value gets copied from heap to stack?

Adam
  • 115
  • 3
  • 9
  • 3
    Freed memory doesn't just 'go away'. It's still there, waiting to be reused. Accessing it, however, is undefined behaviour and the results are therefore unpredictable at best. – Paul Sanders Dec 24 '20 at 12:10
  • @PaulSanders Oh wow, then it explains this behaviour, and it's good to know. Thank you! – Adam Dec 24 '20 at 12:11

1 Answers1

1

I think you just need to read documentation about malloc/free. This question was asked million times in C threads I guess. Here is an example: C - What Happens To Memory After free()?