Dangling pointers in C

Previous
Next

A function returning address:

            A function can return address of aggregate data type variable or user defined data type variable to access the data.

#include<stdio.h>
int* add(int,int);
void main()
{
	int a,b;
	int* c;
	printf("enter two numbers : ");
	scanf("%d%d",&a,&b);
	c = add(a,b);
	printf("sum : %d\n",*c);
}
int* add(int x, int y)
{
	int z;
	z=x+y;
	
}

Dangling pointer:

  • In the above code, add function returns the address of local variable.
  • Local variables will be deleted once the function execution completes.
  • As we return the address of location, the value of that location may change by another function before processing the data.
  • Hence Dangling pointers will not provide accurate results(values).
#include<stdio.h> 
int *fun() 
{ 
    int x = 5; 
    return &x; 
} 
int main() 
{ 
    int *p = fun(); 
    fflush(stdin); 
    printf("%d", *p); 
    return 0; 
}
  • Static variable memory will not be released after function execution.
  • Hence we can easily find the solution for above problem.
#include<stdio.h> 
int *fun() 
{ 
    static int x = 5; 
    return &x; 
} 
int main() 
{ 
    int *p = fun(); 
    fflush(stdin); 
    printf("%d", *p); 
    return 0; 
}
Previous
Next

Add Comment

Courses Enquiry Form