Do I need to free variable 'var' inside of local function func()?.
Code:#include<stdio.h> #include<stdlib.h> void func() { int* var = (int*)malloc(sizeof(*var)); } int main() { func(); return 0; }
Do I need to free variable 'var' inside of local function func()?.
Code:#include<stdio.h> #include<stdlib.h> void func() { int* var = (int*)malloc(sizeof(*var)); } int main() { func(); return 0; }
Generally, you should free what you malloc. It may not be necessary in a modern OS if the process is going to be terminated very soon, but if you're not certain that that will be the case, then there's no harm just freeing anyway.
As for your example: unfortunately it is so pointless that you don't need malloc either, so it's not very useful to comment on whether you need to free anything. Arguably, you don't need the program in the first place
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
> Do I need to free variable 'var' inside of local function func()?.
You either need to free it in func, or return the pointer to the caller so they can free it.
You need to call free at some point, your only choice is where and when.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Code:#include <stdio.h> #include <stdlib.h> int *iota(size_t size) { int *v = malloc(size * sizeof(*v)); if (v) for (size_t i = 0; i < size; ++i) v[i] = i; return v; } void print(const int *a, size_t size) { for (size_t i = 0; i < size; ++i) printf("%d ", a[i]); putchar('\n'); } int main() { const size_t size = 20; int *a = iota(size); if (a) { print(a, size); free(a); } return 0; }
Last edited by john.c; 12-16-2020 at 07:47 AM.
A little inaccuracy saves tons of explanation. - H.H. Munro
Thanks Amanda for your comments.
Thanks.
Thanks Salem and John too for comments.