0

i just wrote a code

int main(void){
    int* B=malloc(sizeof(int));
    printf("%p",B);
}

to check if it allocates different memory every time i run it, but i forgot to add free(); in this, so how can i free that memory now, which has been used by this code to allocate it to the variable B?

ARYAN RAJ
  • 37
  • 5
  • 2
    no worries, the OS reclaims the memory when the process exits. – yano Mar 16 '22 at 20:43
  • Once a process ends, all of its memory is freed. – stark Mar 16 '22 at 20:43
  • so, if it is freed eventually, why should we free it? – ARYAN RAJ Mar 16 '22 at 20:44
  • 2
    It depends, what if your program runs indefinitely, like a web server? In that case, you must free up resources during runtime or you'll exhaust the system. If you _know_ your program allocates only a certain amount and will exit, then you don't have to `free` it. In fact, I've seen users on SO here advocate against `free`ing (in that case), since it introduces the possibility for bugs. – yano Mar 16 '22 at 20:46
  • 2
    One nice thing about ending your program with all memory freed is that if you later have an actual leak and try to find it with some tools like valgrind or leak sanitizer, it'll only show you "real" leaks. It's really annoying to have to resort to suppression files etc to filter out leaks that some libraries have left in there intentionally. – Ted Lyngmo Mar 16 '22 at 20:49

1 Answers1

1

Generally speaking memory is freed when process terminates. It is not a problem with your example code, but not freeing memory instantly when you don't need it anymore is not a good habit. If you are creating stuff for system that has resources close to none, every used byte at runtime counts. If you have a long running process, not freeing memory will show up as a memory leak.

potato_cannon
  • 283
  • 2
  • 9