0

Let us supposed the following code:

#include<stdlib.h>

void func1()
{
    int a=2;
    int b=3;
    int c=4;
}

void func2()
{
    int *ptr; 
    ptr = (int *)malloc(3 * sizeof(int)); 
}

int main()
{
    func1();
    printf("Point 1\n");
    func2();
    printf("Point 2\n");
}

My questions are:

  • What does it happen with the memory allocated for the variables a, b and c (that are local variables in "func1"), after the execution of
    "func1" in the main function? The space required for storing these variables can be reused by other programs after this?
  • What does it happen with the memory allocated for "ptr" (that is local in "func2"), after the execution of "func2"? Should we free the memory before exiting the function?
Zaratruta
  • 2,097
  • 2
  • 20
  • 26
  • Your first question is answered by reading https://en.cppreference.com/w/c/language/storage_duration – Shawn Oct 06 '18 at 15:40
  • For your second question, if you allocate memory with malloc, you should release it with free to avoid leaking memory. – Shawn Oct 06 '18 at 15:42

1 Answers1

1

What does it happen with the memory allocated for the variables a, b and c (that are local variables in "func1"), after the execution of "func1" in the main function?

Local variables are stored on a stack memory, and get popped off when a function exits.

What does it happen with the memory allocated for "ptr" (that is local in "func2"), after the execution of "func2"?

"malloc" allocates memory on the heap, so other processes will not be able to use this memory after your program exits. So yes you should free the allocated memory before exiting.

Resource:

  1. https://www.gribblelab.org/CBootCamp/7_Memory_Stack_vs_Heap.html

  2. Where in memory are my variables stored in C?

alk
  • 69,737
  • 10
  • 105
  • 255
nshimiye
  • 144
  • 1
  • 4
  • 1
    "*"malloc" allocates memory on the heap, so other processes will not be able to use this memory after your program exits*" All implementations at least I know free all memory a process allocated the moment the process ends. – alk Oct 06 '18 at 16:41