edited by
35,087 views
87 votes
87 votes

Consider the following C code:

#include<stdio.h>
int *assignval (int *x, int val) {
    *x = val;
    return x;
}

void main () {
    int *x = malloc(sizeof(int));
    if (NULL == x) return;
    x = assignval (x,0);
    if (x) {
        x = (int *)malloc(sizeof(int));
        if (NULL == x) return;
        x = assignval (x,10);
    }
    printf("%d\n", *x);
    free(x);
}

The code suffers from which one of the following problems:

  1. compiler error as the return of $malloc$ is not typecast appropriately.
  2. compiler error because the comparison should be made as $x == \text{NULL}$ and not as shown.
  3. compiles successfully but execution may result in dangling pointer.
  4. compiles successfully but execution may result in memory leak.
edited by

7 Answers

Best answer
95 votes
95 votes

Answer is D.  

Option A:  
 In C++  we need to do typecasting. C does automatic implicit typecasting. 

See the screenshot for C & C++ compilers below. C compiler is working fine but C++ compiler is giving error.

Option B: Null means address 0.  if $( a == 0)$    if $( 0 == a )$  There is no difference. 

Option C: Do it step by step, always $x$ is pointing to a valid memory location. Dangling Pointer means if it points to a memory location which is deleted(freed). So no dangling pointer.  http://www.geeksforgeeks.org/dangling-void-null-wild-pointers/

Option D: $x$ will loss the previous address it was pointing to. So it will result in memory leakhttp://www.geeksforgeeks.org/what-is-memory-leak-how-can-we-avoid/

Proof for Option A:

C Compiler:


edited by
50 votes
50 votes

$\mathbf{{\color{Blue}Memory\,leak: }}$ 

What happens if some memory is heap allocated, but never deallocated? A program which forgets to deallocate a block is said to have a "memory leak" which may or may not be a serious problem. The result will be that the heap gradually fill up as there continue to be allocation requests, but no deallocation requests to return blocks for re-use. For a program which runs, computes something, and exits immediately, memory leaks are not usually a concern. Such a "one shot" program could omit all of its deallocation requests and still mostly work. Memory leaks are more of a problem for a program which runs for an indeterminate amount of time. In that case, the memory leaks can gradually fill the heap until allocation requests cannot be satisfied, and the program stops working or crashes. Many commercial programs have memory leaks, so that when run for long enough, or with large data-sets, they fill their heaps and crash. Often the error detection and avoidance code for the heap-full error condition is not well tested, precisely because the case is rarely encountered with short runs of the program — that's why filling the heap often results in a real crash instead of a polite error message. Most compilers have a 31 "heap debugging" utility which adds debugging code to a program to track every allocation and deallocation. When an allocation has no matching deallocation, that's a leak, and the heap debugger can help you find them.

is short: a way that memory which is no longer needed is not released or may happen when an object is stored in memory but cannot be accessed by the running code.


$\mathbf{{\color{Blue}Dangling\,pointer: }}$

 pointers that do not point to a valid object of the appropriate type or a pointer becomes dangling when the block of memory it points to is freed.

http://www.geeksforgeeks.org/dangling-void-null-wild-pointers/

http://cslibrary.stanford.edu/102/PointersAndMemory.pdf

https://en.wikipedia.org/wiki/Dangling_pointer

{
   char *dp = NULL;
   {
       char c;
       dp = &c;
   }
     /* c falls out of scope */
     /* dp is now a dangling pointer */
}
                

void func()
{  
    char *dp = malloc(A_CONST);
    free(dp);         /* dp now becomes a dangling pointer */
    dp = NULL;        /* dp is no longer dangling */
}

int *func(void)
{
    int num = 1234;
    /* ... */
    return &num;
}//after returning from func() mem freed 

edited by
39 votes
39 votes

Memory leak In simple words: you create memory dynamically and Forget to detele that memory.

So solution Make that Free(variable) (which contain the address of that variable)

Dangling Problem: You Freed the dynamically allocated memory, But still point to that memory.

So solution Make that variable= null (which contain the address of that variable).


#include<stdio.h>
int *assignval (int *x, int val) {
    *x = val;
    return x;
}

void main () {
    int *x = malloc(sizeof(int));   memory allocated dynamically to *x which point int data.
    if (NULL == x) return;   this case to chcek memory availiable or not if not then x= null is happen
    x = assignval (x,0);  this will make function call and assign *x= 0 and return addrees of same memory
    if (x) {               since x= memory address this condition is true
        x = (int *)malloc(sizeof(int));  New memory assign to x
        if (NULL == x) return;                this is true if memory availiable 
        x = assignval (x,10);                This assign memory location *x= 10.
    }
    printf("%d\n", *x);  print *x= 10 
    free(x);  we freed last allocated memory but not the memory which is assigned 1st time.
}

Dangling problem is arise if we use printf("%d\n", *x); after  free(x);

12 votes
12 votes

Option (D).

 malloc() return  a void type address(like 1201x) ,so no need for typecasting and now x contain a location . now x=assignval(x,0) is called that assign 0 on memory location pointed by x and return x(value of x, not value at address pointed by x). now again x contain same address(1201x).  if( x ) is evaluated to true because x contain a non zero value (1201x) and on x=(int*)malloc(sizeof(int)); assign a new location to x , so we lost the previous memory location because now we have no reference to that location and we can't free that location, so execution may result in memory leak.

points:

malloc() return a void type pointer so no need to typecasting.

x==NULL or NULL==x both are valid.

dangling pointer example

{
   char *dp = NULL;
   /* ... */
   {
       char c;
       dp = &c;
   } 
     /* c falls out of scope */
     /* dp is now a dangling pointer */
}

referance :

http://www.geeksforgeeks.org/what-is-memory-leak-how-can-we-avoid/ 

edited by
Answer:

Related questions

68 votes
68 votes
5 answers
2