Code:void *foo(){ int *x = malloc(56); return x; } int main(){ int *y = foo(); free(y); return 0; }
By freeing 'y' in main function, am I decallocating 'x' in function foo?
Code:void *foo(){ int *x = malloc(56); return x; } int main(){ int *y = foo(); free(y); return 0; }
By freeing 'y' in main function, am I decallocating 'x' in function foo?
x in foo() is just a local variable that temporarily holds the return address from malloc(). When you return to main(), y now holds that same address returned from foo(). x does not exist at this point. Yes, you are correctly freeing up the memory allocated earlier by malloc() in foo().
You can check these things yourself using valgrind. Valgrind can help you check for any memory leaks in your program instantly. What you all have to do is compile your code with debugg option enabled (-g).
Those command should reveal that if your program indeed has a memory or leak free. Good tool to get your hands dirty. It helped me a great deal at times.Code:gcc -Wall -g <youprogram.c> -o <outout> valgrind --leak-check=yes <output>
~H
Life is like riding a bicycle. To keep your balance you must keep moving - Einstein
True, but the OP's code was correct. The OP was just trying to understand what was happening, not how to debug the code. If the OP was taking a course from an instructor, the instructor did not teach the subject very well. I see this too many times.
You have to understand basic C first, before you can understand the results from an excellent tool like valgrind.
Life is like riding a bicycle. To keep your balance you must keep moving - Einstein