Please read Instructions Carefully I need the following 4 q

Please read Instructions Carefully ~ I need the following 4 questions answered for EACH code statement in mem.c which is below the image

MEM.C

#include <stdio.h>

#include <stdlib.h>

#include <malloc.h>

int main() {

   int num;

   int *ptr;

   int **handle;

   num = 14;

   ptr = (int *)malloc(2 * sizeof(int));

   handle = &ptr;

   *ptr = num;

   ptr = &num;

   handle = (int **)malloc(1 * sizeof(int **));

}

(Exercise) Memory Download mem c from the assignment page. Answer the following questions for each code statement in mem.c: C1. What areas of memory (heap or stack) are affected by the statement C2. Does any memory get allocated or freed? C3. If C2 is true then where is this memory? C4. Does the statement result in a memory leak?

Solution


#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

int main() {
int num;
int *ptr;
int **handle;
num = 14;
ptr = (int *)malloc(2 * sizeof(int));
handle = &ptr;
*ptr = num;
ptr = &num;
handle = (int **)malloc(1 * sizeof(int **));
}

C1.   What areas of memory are affected by statements:

   int num; // stack
int *ptr; // stack
int **handle; // stack
num = 14;
ptr = (int *)malloc(2 * sizeof(int)); // heap
handle = &ptr; // stack
*ptr = num; // stack
ptr = &num; // stack
handle = (int **)malloc(1 * sizeof(int **)); // heap


C2.   Does any memory get allocated

   Yes.
   ptr = (int *)malloc(2 * sizeof(int)); // two block of memory get allocated in heap
   handle = (int **)malloc(1 * sizeof(int **)); // 1 block of memory get allocated in heap

C3.
    in heap

C4.
    Yes.

    ptr = (int *)malloc(2 * sizeof(int)); // here we are allocating memory in heap that is hold by \'ptr\'
    Now, ptr = &num; // here now ptr pointing to num, so earlier allocated memory was not
    freed but still available in memory that is not useful

Please read Instructions Carefully ~ I need the following 4 questions answered for EACH code statement in mem.c which is below the image MEM.C #include <stdi
Please read Instructions Carefully ~ I need the following 4 questions answered for EACH code statement in mem.c which is below the image MEM.C #include <stdi

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site