303 views
5 5 votes

What is the main issue in the following code? Assume both $\texttt{malloc()}$ calls succeed.

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

int main() {
    int *p = (int *)malloc(sizeof(int));
    *p = 5;

    p = (int *)malloc(sizeof(int));
    *p = 10;

    printf("%d", *p);

    free(p);

    return 0;
}
  1. It gives compilation error
     
  2. It prints $\texttt{10}$, but the first allocated memory block is leaked
     
  3. It prints $\texttt{5}$, and no memory leak occurs
     
  4. It gives undefined behavior because $\texttt{p}$ is reassigned

2 Answers

0 0 votes

First:

$\texttt{int *p = (int *)malloc(sizeof(int));}$

allocates one integer block on the heap.

Then:

$\texttt{*p = 5;}$

stores $\texttt{5}$ in that first heap block.

Now:

$\texttt{p = (int *)malloc(sizeof(int));}$

allocates a second heap block and stores its address in $\texttt{p}$.

But the address of the first heap block is lost.

Since no pointer now stores the address of the first block, we cannot free it later.

This is called a memory leak.

Then:

$\texttt{*p = 10;}$

stores $\texttt{10}$ in the second heap block.

So:

$\texttt{printf("\%d", *p);}$

prints $\texttt{10}$

Finally:

$\texttt{free(p);}$

frees only the second block.

The first block remains leaked.


Answer: B

Position:
Show:

Related questions

5 5 votes
2 2 answers
304
304 views
GO Classes asked Jun 27
304 views
What is the output of the following code? Assume $\texttt{malloc()}$ succeeds.#include <stdio.h #include <stdlib.h int main() { int *p = (int *)malloc(3 * sizeof(int)); p...
4 4 votes
2 2 answers
303
303 views
GO Classes asked Jun 27
303 views
What will happen in the following code?#include <stdio.h #include <stdlib.h int main() { int *p = (int *)malloc(sizeof(int)); *p = 10; free(p); printf("%d", *p); return 0...
6 6 votes
2 2 answers
265
265 views
GO Classes asked Jun 27
265 views
What is the output of the following code?#include <stdio.h int main() { int x = 25; void *p = &x; printf("%d", *(int *)p); return 0; }$\texttt{25}$ Address of $\texttt{x}...
7 7 votes
2 2 answers
306
306 views
GO Classes asked Jun 27
306 views
Which of the following correctly describes the declarations?int *a[10]; int (*p)[5];$\texttt{a}$ is a pointer to an array of $10$ integers, and $\texttt{p}$ is an array o...