The Gateway to Computer Science Excellence
+29 votes
7.1k views

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 == 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.
in Programming by Veteran (425k points)
edited by | 7.1k views
+1
i think answer should be A as malloc allocates memory and returns void pointer pointing to that memory location...it needs to be typecasted right?
0
Result of malloc need not be typecasted bcoz void* can be implicitly converted to any other type.

Read above link by debashish

6 Answers

+42 votes
Best answer

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:


by Boss (12.2k points)
edited by
0
@Arjun Sir, Can u verify this pls?
+1

U compiled using C++ .......do it with C compiler ....it executes without any errors .....

0

void* is compatible with any type no need for type casting.

The Function malloc is most commonly used to attempt to ``grab'' a continuous portion of memory. It is defined by:

   void *malloc(size_t number_of_bytes)

That is to say it returns a pointer of type void * that is the start in memory of the reserved portion of size number_of_bytes. If memory cannot be allocated a NULL pointer is returned.

Since a void * is returned the C standard states that this pointer can be converted to any type. The size_t argument type is defined in stdlib.h and is an unsigned type.

So:


    char *cp;
		 cp = malloc(100);

attempts to get 100 bytes and assigns the start address to cp.

Also it is usual to use the sizeof() function to specify the number of bytes:


    int *ip;
		 ip = (int *) malloc(100*sizeof(int));

Some C compilers may require to cast the type of conversion. The (int *) means coercion to an integer pointer. Coercion to the correct pointer type is very important to ensure pointer arithmetic is performed correctly. I personally use it as a means of ensuring that I am totally correct in my coding and use cast all the time.

It is good practice to use sizeof() even if you know the actual size you want -- it makes for device independent (portable) code.

sizeof can be used to find the size of any data type, variable or structure. Simply supply one of these as an argument to the function.

reference:

http://users.cs.cf.ac.uk/Dave.Marshall/C/node11.html#SECTION001110000000000000000

see malloc specification in this link

0

@Ahwan plz tell me

#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));
        free(x);// if free replaces to here
        if (NULL == x) return;
        x = assignval (x,10);
    }
    printf("%d\n", *x);
    
}

if I replace free to there , will that be a dangling pointer issue? and from where r u sure it is a memory leak?

+14
@srestha  memory leak is due to the prev one. There are 2 malloc.  You are losing reference to that 1st memory location which is allocated. So memory leak.  
So D is correct for sure.

By the way dangling pointer issue exists in the last line I guess. Because that location is freed but x still points to it,  But after it we have nothing to execute, main function ends there. So pointer variable x will also be deleted immediately.
0

But In this line x= assignval(x,0) x(main x) will point to something which is not valid anymore because 

x(assignval local x) is local variable in assignval and goes out of scope after an execution of assignval() get over. and then again inside if statement because of x=assignval(x,0), x will point to some invalid, then why its not dangling?

+1

@prachigupta   You do it again,   just rename that local variable x to x1 & do this qsn again.  assignval( ) is returning the address of that location which x was previously pointing to.

to assignval you passed the address which x is pointing to...
Then assignval returned the same address...so it is just overwritten. 

(It is not pass by value.  It is pass by reference)  Just rename that x to x1 if you are getting confused.

+2

@prachigupta  That local variable x is deleted immediately after function returns. Right ? So why there will be dangling pointer issue ?
While u r second time calling it, u r passing address of new location to which x points to.

0

@Ahwan

 free(x);// when this last statement is executed,then after that x is not set to NULL.So can i say x is my dangling pointer.I agree that memory leak is abvious in this code.But can i say it has dangling pointer also?
0
When in assignval(int *x ,int val) function it return x what is that x ?

is it address store in x or value of of address stored in x?
0
Here the pointer *x was declared as int, and it was implicitly type cast. What if it was declared as void *x??

Will it be implicitly type cast like before?
0
memory leak here by first X allocation
+24 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 

by Loyal (6.8k points)
edited by
0
After executing free(x); we delete the memory but  pointer 'x' point to same memory then why x is not dangling pointer?
0

(read yellow line) wiki: if the original program then dereferences the (now) dangling pointer, unpredicted behavior may result, as memory may now contain completely different data.

but in this program we are not going to use data from the object which reference previously was deallocated.

+15 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);

by Boss (18.7k points)
+10 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/ 

by (323 points)
edited by
0
that codepath is never taken, if(x) which evaluates to if(0) is there right ?
+1
No, in if condition x is there ,not *x and x hold a location that is a non zero value so that control path is taken .
0
Yes you are correct, I guess I missed that part.
0
Can you explain why option(c) is wrong ???
+1

A dangling pointer points to memory that has already been freed. The storage is no longer allocated. Trying to access it might cause a Segmentation fault.

Common way to end up with a dangling pointer:

char* func()
{
   char str[10];
   strcpy(str,"Hello!");
   return(str); 
}
//returned pointer points to str which has gone out of scope. 

You are returning an address which was a local variable, which would have gone out of scope by the time control was returned to the calling function. (Undefined behaviour)

Another common dangling pointer example is an access of a memory location via pointer, after free has been explicitly called on that memory.

int *c = malloc(sizeof(int));
free(c);
*c = 3; //writing to freed location

there is no dangling pointer in this code.

so option (c) is not true.

check this difference:

http://stackoverflow.com/questions/13132798/difference-between-dangling-pointer-and-memory-leak

0
int *c = malloc(sizeof(int));

free(c);

If we only do this then 'c' is not a dangling ptr? But it is pointing to a memory location that is no longer allocated.
0
#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));
        free(x);// if free replaces to here
        if (NULL == x) return;
        x = assignval (x,10);
    }
    printf("%d\n", *x);
    
}

if I replace free to there , will that be a dangling pointer issue?

+1 vote
memory leak in iF Stmt.
by (49 points)
+1 vote

Option B is plain stupid. Ignore it.

Option A isn't necessary, because programming language C does implicit typecasting.


So, we're left with Options C and D

Now, dangling pointer is (using) a pointer that points to nowhere / garbage value.

Memory leak is a piece of memory in the heap, that can't be accessed because the pointer for it is deleted off.

Now, see the code. Are we clearing a pointer? Yes, we are.

Here: 

    free(x);

After doing so, we're terminating the program, and not using the pointer x again. We'll never access x, which currently is freed (points to nowhere). So, no dangling pointer.

 

Is there a memory leak?

Trick: To immediately detect a memory leak in the code, try to find two successive assignments to a pointer, without clearing the pointer first.

    int *x = malloc(sizeof(int));
    x = assignval (x,0);

We assigned the pointer a heap-address and a value.

Then, we did this inside the if-statement

        x = (int *)malloc(sizeof(int));
        x = assignval (x,10);

New memory location assigned to x, and x points to it now. Nothing points to the previous location, hence memory leak

 

Option D.

by Active (2.2k points)
edited ago by

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,644 questions
56,509 answers
195,558 comments
101,068 users